以下方法应该计算给定集合中每个项目的出现次数:
void groupBy(String[] stuff) {
LinkedHashMap<String, AtomicInteger> A = new LinkedHashMap<String, AtomicInteger>();
final AtomicInteger one = new AtomicInteger(1);
AtomicInteger count;
for (String key:stuff) {
count = A.get(key);
if (count==null) A.put(key, one);
else System.out.println("Previous value :"+A.put(key, new AtomicInteger(count.incrementAndGet())));
}
Set set = A.entrySet();
Iterator ii = set.iterator();
while(ii.hasNext()) {
Map.Entry me = (Map.Entry)ii.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
所以,如果我在参数上运行它
String a[] = {"AAA", "A", "AA", "B", "A", "AAA"};
我应该得到
Previous value :1
Previous value :1
AAA: 2
A: 2
AA: 1
B: 1
但是,我得到的是
Previous value :2
Previous value :3
AAA: 3
A: 2
AA: 3
B: 3
散列中的值更新超出了我打算做的,我不知道如何。
帮助表示赞赏。