![](/img/trans.png)
[英]Java - .putAll( t ) into a hashmap puts also t into another hashmap
[英]HashMap put or putAll? - Java
通过引用放置哈希图,并通过副本放置哈希图。 我该怎么办? 另一个问题是String[] types
数量并不是真正已知的,因此创建Multiset<String> textAndCount = TreeMultiset.create();
多个实例Multiset<String> textAndCount = TreeMultiset.create();
不是很有帮助。 我有以下代码,但是两种类型的输出都相同。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.Multiset;
import com.google.common.collect.TreeMultiset;
public class TestIterator {
private static String[] foobarness = {"foo", "bar", "ness", "foo", "bar", "foo", "ness", "bar", "foo", "ness", "foo", "bar", "foo", "ness", "bar", "ness", "foo", "bar", "foo", "ness"};
private static String[] foobarness2 = {"bar", "ness", "foo", "bar", "foo", "ness", "bar", "foo", "ness", "foo", "foo", "bar", "foo", "ness", "bar", "foo", "ness", "bar", "foo", "ness", "ness", "bar", "foo", "ness"};
private static String[] types = {"type::1", "type::2"};
public static void main(String[] args) {
Map<String, Multiset<String>> typeTextCount =
new HashMap<String, Multiset<String>>();
Multiset<String> textAndCount = TreeMultiset.create();
for (int i = 0; i < types.length; i++) {
if ("type::1".equals(types[i])) {
for (String text : foobarness)
textAndCount.add(text, 1);
}
if ("type::2".equals(types[i])) {
for (String text : foobarness2)
textAndCount.add(text, 1);
}
typeTextCount.put(types[i], textAndCount);
}
Iterator<Entry<String, Multiset<String>>> itTTC =
typeTextCount.entrySet().iterator();
while (itTTC.hasNext()) {
Map.Entry textCt = (Map.Entry) itTTC.next();
System.out.println(textCt.getKey() + " :\t" + textCt.getValue());
itTTC.remove();
}
}
我的输出来自上面的代码:
type::2 : [bar x 13, foo x 17, ness x 14]
type::1 : [bar x 13, foo x 17, ness x 14]
正确的输出应为:
type::1 : [bar x 6, foo x 8, ness x 6]
type::2 : [bar x 7, foo x 9, ness x 8]
在您的for循环中移动Multiset<String> textAndCount = TreeMultiset.create()
。 两个“类型”都共享相同的多集,因此您的计数增加了一倍。
您的for循环可能如下所示:
for (int i = 0; i < types.length; i++) {
Multiset<String> textAndCount = TreeMultiset.create();
if ("type::1".equals(types[i])) {
for (String text : foobarness)
textAndCount.add(text, 1);
}
if ("type::2".equals(types[i])) {
for (String text : foobarness2)
textAndCount.add(text, 1);
}
typeTextCount.put(types[i], textAndCount);
}
在使用它的同时,还可以通过使用for-each样式循环来改进地图的迭代。 如果你遍历这是热衷于消除每个条目,你可以换你的entrySet一个consumingIterable
为相同的功能。
for (Entry<String, Multiset<String>> textCt : Iterables.consumingIterable(typeTextCount
.entrySet())) {
System.out.println(textCt.getKey() + " :\t" + textCt.getValue());
}
这产生输出:
type::2 : [bar x 7, foo x 9, ness x 8]
type::1 : [bar x 6, foo x 8, ness x 6]
如果您不喜欢该命令,建议您使用“ Ordering
来获取条目的排序列表。
Multiset<String> textAndCount = TreeMultiset.create();
应该在循环内。 如果您放入该设置的副本,则输出为
type::1 : [bar x 6, foo x 8, ness x 6] type::2 : [bar x 13, foo x 17, ness x 14]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.