java stream groupingBy

package com;
import java.util.*;
import java.util.stream.Collectors;


public class App2 {
    public static void main(String[] args) {
        List<String> list = Arrays.asList(
                "wang",
                "wang",
                "wei",
                "lili");
        // 按字符串长度分组,只提供key,默认是以List作为value,HashMap作为结果
        Map<Integer, List<String>> map0 = list.stream().collect(Collectors.groupingBy(x->x.length()));
        // 按字符串长度分组,(无重复),提供key,提供Set作为value,默认HashMap作为结果
        Map<Integer, Set<String>> map1 = list.stream().collect(Collectors.groupingBy(x->x.length(), Collectors.toSet()));
        // 按照年龄分组(无重复 + 保持插入顺序),提供key,提供Set作为value,默认LinkedHashMapMap作为结果
        Map<Integer, Set<String>> map2 = list.stream().collect(Collectors.groupingBy(x->x.length(), LinkedHashMap::new, Collectors.toSet()));
        System.out.println(map0);
        System.out.println(map1);
        System.out.println(map2);
    }
}

参考:
https://blog.csdn.net/xiaolulululululu/article/details/101378439

你可能感兴趣的:(java)