Java whit frequency中的倒置哈希映射
我有一个Java whit frequency中的倒置哈希映射,java,Java,我有一个HashMap,我想创建一个hashMapInverted,它在键中包含列表、第一个映射的值以及在第一个映射中具有相同列表的字符串集的值 我该怎么做呢?你可以试试- Map<String, LinkedList<Integer>> map =new HashMap<String, LinkedList<Integer>>(); Map<LinkedList<Integer>, Set<String>> i
HashMap
,我想创建一个hashMapInverted
,它在键中包含列表、第一个映射的值以及在第一个映射中具有相同列表的字符串集的值
我该怎么做呢?你可以试试-
Map<String, LinkedList<Integer>> map =new HashMap<String, LinkedList<Integer>>();
Map<LinkedList<Integer>, Set<String>> invertMap = new HashMap<LinkedList<Integer>, Set<String>>();
for (Entry<String, LinkedList<Integer>> entry : map.entrySet()) {
if(invertMap.containsKey(entry.getValue())){
invertMap.get(entry.getValue()).add(entry.getKey());
}else{
Set<String> set = new HashSet<String>();
set.add(entry.getKey());
invertMap.put(entry.getValue(), set);
}
}
Map Map=newhashmap();
Map invertMap=newhashmap();
for(条目:map.entrySet()){
if(invertMap.containsKey(entry.getValue())){
获取(entry.getValue()).add(entry.getKey());
}否则{
Set=newhashset();
set.add(entry.getKey());
invertMap.put(entry.getValue(),set);
}
}
您可以执行以下操作:
Map<LinkedList<Integer>, Set<String>> mapInverted = new HashMap<>(myMap.size());
for(Entry<<String, LinkedList<Integer>> entry : myMap.entrySet()) {
String key = entry.getKey();
LinkedList<Integer> list = entry.getValue();
Set<String> strings = mapInverted.get(list);
if(strings == null) { // the list has not already been put in the map
strings = new HashSet<String>(); // create a new set
mapInverted.put(list, strings); // put the list and the new set
}
strings.add(key);
}
Map-mapInverted=newhashmap(myMap.size());
对于(entry)您是否已尝试在第一个映射上循环以填充新映射?OP希望新映射为map
map invertMap=new HashMap();
返回映射是一个全新的映射。初始映射中的值不是唯一的,因此反转映射中的值是一个集合,而不是单个项目。出于同样的原因,BiMap无法工作…(至少我理解OP所说的)@assylias您的理解是100%正确的,非常感谢您的评论。:)