Stream流进行集合处理的常用方法

Java8使用Stream流操作集合真香啊,下面整理了一些平时在工作中使用频繁的操作集合的方法,肯定是不够全面的,后续有用到其他的,会再来补充。

  • 集合转换操作:

public class StreamDealCollections {

    public static void main(String[] args) {
        // 创建一个list集合
        List userList = Arrays.asList(
                new Student("001","小明", 14, "女"),
                new Student("002","小红", 16, "女"),
                new Student("003","小刚", 24, "女"),
                new Student("004","小钢炮", 14, "女"),
                new Student("005","小钢管", 16, "女")
        );

        // 根据num值对集合进行过滤
        List studentList = userList.stream().filter(student -> student.getNum().equals("003")).collect(Collectors.toList());
        ShowStudentList(studentList);

        // 集合转Map,当键重复时候采用Key1(如果没有(key1, key2) -> key1) 那么有重复的Key时,会报java.lang.IllegalStateException)
        Map map = userList.stream().collect(Collectors.toMap(Student::getNum, Student::getName, (key1, key2) -> key1));
        ShowMap(map);

       //  遍历集合,取出num列表
        Set set = userList.stream().map(Student::getNum).collect(Collectors.toSet());
        ShowStringList(new ArrayList(set));

        // 根据num分类,key为num value为name集合(为什么是集合?因为可能存在key一样的情况,key一样时就是个name集合)
        Map> setMap = userList.stream().collect(Collectors.groupingBy(Student::getNum, Collectors.mapping(Student::getName, Collectors.toSet())));
        ShowSetMap(setMap);

        // 根据num分类,值为Student集合
        Map> listMap = userList.stream().collect(Collectors.groupingBy(Student::getNum));
        ShowListMap(listMap);

        // 根据num分类,num需要唯一
        Map studentMap = userList.stream().collect(Collectors.toMap(Student::getNum, Function.identity()));

        // 将List转换成treemap
        TreeMap treeMap = userList.stream()
                .sorted(Comparator.comparing(Student::getName))
                .collect(Collectors.toMap(Student::getName, Function.identity(), (o1, o2) -> o1, TreeMap::new));

        // 将List转换成ConcurrentHashMap
        ConcurrentHashMap concurrentHashMap = userList.stream().collect(Collectors.toMap(Student::getNum, Function.identity(),
                (o1, o2) -> o1, ConcurrentHashMap::new));

    }

    private static void ShowStringList(List list) {
        System.out.println("======================================");
        list.stream().forEach(l->{
            System.out.println(l);
        });
    }
    private static void ShowStudentList(List list) {
        System.out.println("======================================");
        list.stream().forEach(coll->{
            System.out.println(coll);
        });
    }
    private static void ShowMap(Map map) {
        System.out.println("======================================");
        map.forEach((k,v)->{
            System.out.println("Key: "+k+" Value: "+v);
        });
    }
    private static void ShowSetMap(Map> map) {
        System.out.println("======================================");
        map.forEach((k,v)->{
            System.out.println("Key: "+k+" Value: "+v.toString());
        });
    }
    private static void ShowListMap(Map> map) {
        System.out.println("======================================");
        map.forEach((k,v)->{
            System.out.println("Key: "+k+" Value: "+v.toString());
        });
    }
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    static class Student{
        // 学号
        private String num;
        // 姓名
        private String name;
        // 年龄
        private Integer age;
        // 性别
        private String gender;
    }

}
  • 两个集合间的操作
 // 交集
 List intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());

// 差集 (list1 - list2)
List reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
 
 // 差集 (list2 - list1)
List reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());

// 并集
List listAll = list1.parallelStream().collect(Collectors.toList());
List listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);

// 去重并集
List listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());
        
// 根据id去重
allRoleList.stream().filter(distinctByKey(e -> e.getId())).collect(Collectors.toList());

 

你可能感兴趣的:(Java,stream,lambda,集合)