分组对象列表并使用Java集合进行计数
发布时间:2020-12-15 04:35:46 所属栏目:Java 来源:网络整理
导读:哪个 Java Collection类更好地对对象列表进行分组? 我有一个来自以下用户的消息列表: aaa hibbb helloccc Gmaaa Can?CCC yesddd No 从我想要计数的消息对象列表中,显示aaa(2)bbb(1)ccc(2)ddd(1).任何代码帮助? 解决方法 从其他几个答案中将各个部分放在一
哪个
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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |