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