java8 stream流操作实现List Count/Word Count

2020-11-11 17:35:35 浏览数 (1)

话不多说,直接上代码

  • List Count
代码语言:javascript复制
public static void main(String[] args) {
    List<String> list = Arrays.asList("beijing", "shanghai", "guangzhou", "shenzhen", "beijing");
    Map<String, Long> collect = list.stream()
            .collect(Collectors.groupingBy(o -> o, Collectors.counting()));
    System.out.println(collect);
    // out => {guangzhou=1, shanghai=1, shenzhen=1, beijing=2}
}
  • List Word Count
代码语言:javascript复制
public static void main(String[] args) {
    List<String> list = Arrays.asList("beijing shanghai guangzhou"
                                    , "beijing guangzhou"
                                    , "beijing", "beijing");
    Map<String, Long> collect = list.stream()
            .flatMap(o -> Stream.of(o.split(" ")))
            .collect(Collectors.groupingBy(o -> o, Collectors.counting()));
    System.out.println(collect);
    // out => {guangzhou=2, shanghai=1, beijing=4}
}
如果要包含元素
  • 使用JDK自带集合类
代码语言:javascript复制
public static void main(String[] args) {
    List<String> list = Arrays.asList("beijing", "shanghai", "guangzhou", "shenzhen", "beijing");
    Map<String, List<String>> collect
            = list.stream().collect(Collectors.groupingBy(o -> o));
    System.out.println(collect);
    // out => {guangzhou=[guangzhou], shanghai=[shanghai], shenzhen=[shenzhen], beijing=[beijing, beijing]}
}
  • 使用SpringLinkedMultiValueMap
代码语言:javascript复制
public static void main(String[] args) {
    List<String> list = Arrays.asList("beijing", "shanghai", "guangzhou", "shenzhen", "beijing");
    LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap();
    list.stream().forEach(o -> map.add(o, o));
    System.out.println(map);
    // out => {beijing=[beijing, beijing], shanghai=[shanghai], guangzhou=[guangzhou], shenzhen=[shenzhen]}
}

0 人点赞