java8-lambda-list中字符出现字数的统计
2024-10-18 16:28:11
@Test
public void testStringCount(){
List<String> moidList1 = new ArrayList<>();
moidList1.add("1");
moidList1.add("2");
moidList1.add("2");
moidList1.add("3");
moidList1.add("3");
moidList1.add("3");
moidList1.add("4");
moidList1.add("4");
moidList1.add("4");
moidList1.add("4");
Map<String, Long> map1 = moidList1.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("moid出现次数统计(moid=次数):" + map1);
List<Map.Entry<String, Long>> list1 = new ArrayList<>(map1.entrySet());
Collections.sort(list1, new Comparator<Map.Entry<String, Long>>()
{
@Override
public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2)
{
//按照value值,从小到大排序
// return o1.getValue() - o2.getValue();
//按照value值,从大到小排序
// return o2.getValue() - o1.getValue();
//按照value值,用compareTo()方法默认是从小到大排序
return o2.getValue().compareTo(o1.getValue());
}
});
for (Map.Entry s : list1)
{
System.out.println("出现次数最多的moid:" + s.getKey()+"--"+s.getValue());
}
}
执行结果:
moid出现次数统计(moid=次数):{1=1, 2=2, 3=3, 4=4}
出现次数最多的moid:4--4
出现次数最多的moid:3--3
出现次数最多的moid:2--2
出现次数最多的moid:1--1
如果元素是int型,需要拿到出现次数最多的数字,则可以用下列方法(未测试,从其他地方拷贝的):
int[] arr = {1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5};
// 过程1 Collectors.groupingBy代表是分类,按照本身Function.identity()进行分类,那相同数字就会放在一起,Collectors.counting是统计相同数字的个数
Map<Integer, Long> map = IntStream.of(arr).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("数字出现次数统计(数字=次数):" + map);
// 过程2 max方法是根据比较器(按照map的value进行排序)找出最大值
Optional<Integer> maxOptional = map.entrySet().stream().max(Comparator.comparing(Map.Entry::getValue)).map(Map.Entry::getKey);
System.out.println("出现次数最多的数字:" + maxOptional.get());
最新文章
- Moving in Unity
- JavaScript高级程序设计之函数
- hdu 3311 斯坦纳树
- 关于 error: LNK1123: failure during conversion to COFF: file invalid or corrupt 错误的解决方案【Qt】【 VS2010】
- compress 表设置及索引设置
- Objective-C之消息机制
- C++静态库与动态库(简介)
- windows server 2012 AD 活动目录部署系列(五)备份和还原域控制器
- ionic build android 中的报错详细原因以及解决方法
- golang变量作用域问题-避免使用全局变量
- openlayers4 入门开发系列之地图模态层篇(附源码下载)
- Ffmpeg使用
- halcon几何变换(仿射变换)
- MySQL性能测试工具sysbench的安装和使用
- Guava Finalizer
- uri 定义
- Android之Activity界面跳转--生命周期方法调用顺序
- Java从零开始学二十一(集合List接口)
- cdoj915-方老师的分身 II (长度不小于k的最短路)【spfa】
- Redis+Keepalived高可用方案详细分析