分组对象列表并使用Java集合进行计数

哪个 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)

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...