Group object lists and count them using java collections

Which Java collection class better groups object lists?

I have a list of messages from the following users:

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

From the list of message objects I want to count, display AAA (2) BBB (1) CCC (2) DDD (1) Any code help?

Solution

Put the parts together from several other answers, adjust your code from another question, and fix some trivial errors:

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

This print:

aaa(2)+bbb(1)+ccc(2)+ddd(1)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>