gpt4 book ai didi

java guava multimap 以特定格式输出

转载 作者:行者123 更新时间:2023-12-01 11:06:44 25 4
gpt4 key购买 nike

我有以下 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
Values = [10, 0, 0, 4, 0, 0, 2, 0, 0]
Key = B
Values = [0, 11, 0, 0, 6, 0, 0, 0, 0]
Key = C
Values = [0, 0, 5, 0, 0, 8, 0, 0, 7]

但我需要以下格式的输出:

Key = A
Values = [10, 4, 2]
Key = B
Values = [11, 6, 0]
Key = C
Values = [5, 8, 7]

最佳答案

您应该使用HashMultimap而不是ArrayListMultimap

Multimap<String, Integer> mm = HashMultimap.create();

或者,如果 HashMultimap 对您来说还不够,您可以在将其放入多重映射之前检查该值。

if(!mm.containsValue(10)){
mm.put("A", 10);
}

关于java guava multimap 以特定格式输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32874630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com