天天看點

java stream 統計元素出現次數,并按次數高低進行輸出

package com.my.app.stream;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Description 統計次數,并按次數高低進行輸出
 */
public class Count {

  public static void main(String[] args) {
    String[] names = {"張三", "張三", "李四", "李四", "李四", "李四", "王五", "A", "B", "C", "C"};
    // 僅輸出按次數排序後的元素
    List<String> finalList = Stream.of(names)
                                   .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                                   .entrySet()
                                   .stream()
                                   .sorted((v1, v2) -> v2.getValue().compareTo(v1.getValue()))
                                   .map(Map.Entry::getKey)
                                   .collect(Collectors.toList());
    System.out.println(finalList);
    // 輸出按次數排序後的元素和次數
    Map<String, Long> finalMap = Stream.of(names)
                                       .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                                       .entrySet()
                                       .stream()
                                       .sorted((v1, v2) -> v2.getValue().compareTo(v1.getValue()))
                                       .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (m1, m2) -> m2,
                                                                 LinkedHashMap::new));
    System.out.println(finalMap);


  }
}

           

輸出結果:

[李四, 張三, C, A, B, 王五]
{李四=4, 張三=2, C=2, A=1, B=1, 王五=1}