我正在尝试使用Map来反转键和值,然后将新值组合到Set中。
例如,
Map<String, String> favoriteColors = new HashMap<String, String>();
favoriteColors.put("Jacob", "Red");
favoriteColors.put("Mason", "Blue");
favoriteColors.put("Ethan", "Green");
favoriteColors.put("William", "Red"); reverseMapping(favoriteColors).entrySet()`
会返回
红=(雅各布,威廉),蓝=(梅森),格林=(伊桑)
我甚至不确定从哪里开始。
我已经考虑过迭代原始地图,但我想不出为每种不同的颜色创建新的,独特的集合的方法。
答案 0 :(得分:3)
当提及 Bohemian 时,我建议您使用Guava的Multimap
。
例如:
final Map<String, String> favoriteColors = new HashMap<>();
favoriteColors.put("Jacob", "Red");
favoriteColors.put("Mason", "Blue");
favoriteColors.put("Ethan", "Green");
favoriteColors.put("William", "Red");
final Multimap<String, String> map = Multimaps.forMap(favoriteColors);
final Multimap<String, String> inverted = ArrayListMultimap.create();
Multimaps.invertFrom(map, inverted);
System.out.println(inverted);
输出:
{Blue=[Mason], Red=[William, Jacob], Green=[Ethan]}
答案 1 :(得分:0)
只是简单的Java:
private Map<String, Set<String>> reverseMap(Map<String, String> map) {
Collection<String> values = map.values();
Iterator<String> it = values.iterator();
Map<String, Set<String>> reverseMap = new HashMap<String, Set<String>>();
while(it.hasNext()) {
String val = it.next();
Set<String> set = new HashSet<String>();
reverseMap.put(val, set);
}
Set<String> keys = map.keySet();
for (String key:keys) {
String val = map.get(key);
Set<String> set = reverseMap.get(val);
set.add(key);
}
return reverseMap;
}
以下代码:
Map<String, String> map = new HashMap<String, String>();
map.put("John", "Red");
map.put("Pepe", "Blue");
map.put("Myself", "Red");
Map<String, Set<String>> out = reverseMap(map);
System.out.println(out);
产地:
{Blue=[Pepe], Red=[John, Myself]}