对对象列表进行分组并使用Java集合进行计数 [英] grouping List of Objects and counting using Java collection

查看:164
本文介绍了对对象列表进行分组并使用Java集合进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Which Java Collection class is better to group the list of objects?

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

I have a list of messages from users like below:

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

从此消息对象列表中我想计算并显示 aaa(2)+ bbb(1)+ ccc(2)+ ddd(1)。有代码帮助吗?

From this list of message object I want to count and display aaa(2)+bbb(1)+ccc(2)+ddd(1). Any code help?

推荐答案

将其他几个答案拼凑在一起,以适应另一个问题中的代码,并且修复一些琐碎的错误:

Putting the pieces together from a couple of the other answers, adapting to your code from the other question and fixing a few 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);

此打印:

aaa(2)+bbb(1)+ccc(2)+ddd(1)

这篇关于对对象列表进行分组并使用Java集合进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆