哪个Java Collection类最好对对象列表进行分组?

我有来自以下用户的消息列表:

aaa hi
bbb hello
ccc Gm
aaa  Can?
CCC   yes
ddd   No

从这个消息对象列表中,我想计数并显示aaa(2)+bbb(1)+ccc(2)+ddd(1)。有任何代码帮助吗?

最佳答案

将其他几个答案放在一起,根据另一个问题适应您的代码并修复一些琐碎的错误:

    // 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)

10-06 12:08