哪个
Java Collection类更好地对对象列表进行分组?
aaa hi bbb hello ccc Gm aaa Can? CCC yes ddd No
解决方法
从其他几个答案中将各个部分放在一起,从另一个问题调整您的代码并修复一些琐碎的错误:
// as you want a sorted list of keys,you should use a TreeMap Map<String,Integer> stringsWithCount = new TreeMap<>(); for (Message msg : convinfo.messages) { // where ever your input comes from: turn it into lower case,// so that "ccc" and "CCC" go for the same counter String item = msg.userName.toLowerCase(); if (stringsWithCount.containsKey(item)) { stringsWithCount.put(item,stringsWithCount.get(item) + 1); } else { stringsWithCount.put(item,1); } } String result = stringsWithCount .entrySet() .stream() .map(entry -> entry.getKey() + '(' + entry.getValue() + ')') .collect(Collectors.joining("+")); System.out.println(result);
这打印:
aaa(2)+bbb(1)+ccc(2)+ddd(1)