我有以下MultiMap:
Multimap<String, Integer> mm = ArrayListMultimap.create();
mm.put("A", 10);
mm.put("B", 0);
mm.put("C", 0);
mm.put("A", 0);
mm.put("B", 11);
mm.put("C", 0);
mm.put("A", 0);
mm.put("B", 0);
mm.put("C", 5);
mm.put("A", 4);
mm.put("B", 0);
mm.put("C", 0);
mm.put("A", 0);
mm.put("B", 6);
mm.put("C", 0);
mm.put("A", 0);
mm.put("B", 0);
mm.put("C", 8);
mm.put("A", 2);
mm.put("B", 0);
mm.put("C", 0);
mm.put("A", 0);
mm.put("B", 0);
mm.put("C", 0);
mm.put("A", 0);
mm.put("B", 0);
mm.put("C", 7);
Set<String> keys = mm.keySet();
for (String key : keys) {
System.out.println("Key = " + key);
System.out.println("Values = " + mm.get(key));
}
我得到以下输出:
Key = A
值= [10,0,0,4,0,0,2,0,0]
键= B
值= [0,11,0,0,6,0,0,0,0]
键= C
值= [0,0,5,0,0,0,0,0,7]
但我需要格式为
的输出Key = A
值= [10,4,2]
键= B
值= [11,6,0]
键= C
值= [5,8,7]
答案 0 :(得分:1)
您应该使用Multimap<String, Integer> mm = HashMultimap.create();
代替HashMultimap
if(!mm.containsValue(10)){
mm.put("A", 10);
}
或者如果{{1}}对您来说不够,您可以在将值放入多图之前检查该值。
{{1}}
答案 1 :(得分:0)
使用Multiset
而非Multimap
可以更轻松地解决您的使用案例。首先编写一个辅助方法:
static <T> void addNTimes(Multiset<T> multiset, T item, int n) {
multiset.addAll(Collections.nCopies(item, n));
}
现在您可以重写代码:
Multiset<String> mm = HashMultiset.create();
addNTimes(mm, "A", 10);
addNTimes(mm, "B", 0);
addNTimes(mm, "C", 0);
addNTimes(mm, "A", 0);
addNTimes(mm, "B", 11);
addNTimes(mm, "C", 0);
Set<Entry<String>> keys = mm.entrySet();
for (Entry<String> entry : keys) {
System.out.println("Key = " + entry.getElement());
System.out.println("Values = " + entry.getCount());
}