@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());

最新文章

  1. Moving in Unity
  2. JavaScript高级程序设计之函数
  3. hdu 3311 斯坦纳树
  4. 关于 error: LNK1123: failure during conversion to COFF: file invalid or corrupt 错误的解决方案【Qt】【 VS2010】
  5. compress 表设置及索引设置
  6. Objective-C之消息机制
  7. C++静态库与动态库(简介)
  8. windows server 2012 AD 活动目录部署系列(五)备份和还原域控制器
  9. ionic build android 中的报错详细原因以及解决方法
  10. golang变量作用域问题-避免使用全局变量
  11. openlayers4 入门开发系列之地图模态层篇(附源码下载)
  12. Ffmpeg使用
  13. halcon几何变换(仿射变换)
  14. MySQL性能测试工具sysbench的安装和使用
  15. Guava Finalizer
  16. uri 定义
  17. Android之Activity界面跳转--生命周期方法调用顺序
  18. Java从零开始学二十一(集合List接口)
  19. cdoj915-方老师的分身 II (长度不小于k的最短路)【spfa】
  20. Redis+Keepalived高可用方案详细分析

热门文章

  1. day53 Pyhton 前端04
  2. centos8平台基于iftop监控网络流量
  3. 判断ip地址是属于国内还是国外
  4. html中object标签
  5. 用python和GDAL 读取GRIB数据
  6. python的部分GUI模块简介tkinter、pyqt5(Qt Designer)
  7. ElementUI级联选择器动态加载Demo
  8. 基于risc-v架构cpu
  9. Spring Boot与多数据源那点事儿~
  10. 购买GPRS DTU时应该怎么选择