Java8集合常用操作

110 阅读1分钟
package com.hmy.uaa;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        Student st1 = new Student(1, "张三", 10);
        Student st2 = new Student(1, "张三", 10);
        Student st3 = new Student(2, "李四", 11);
        Student st4 = new Student(3, "王五", 10);
        List<Student> list = new ArrayList<>();
        list.add(st1);
        list.add(st2);
        list.add(st3);
        list.add(st4);
        System.out.println("原信息:" + list);
        // 去重
        // 注意是否要重写equals和hashcode
        List<Student> noRepeatList = list.stream().distinct().collect(Collectors.toList());
        System.out.println("去重后:" + noRepeatList);

        list不去重,set去重,map中key相同时覆盖
        // 取集合中某个字段值
        List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList());
        System.out.println("取集合中的年龄list:" + ageList);

        // 取集合中某个字段值
        Set<Integer> setList = list.stream().map(Student::getAge).collect(Collectors.toSet());
        System.out.println("取集合中的年龄set:" + setList);

        // List转map key字段,value对象
        Map<Integer, Student> studentMap =
                list.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (key1, key2) -> key2));
        System.out.println("List转map key字段,value对象: " + studentMap);

        // List转map key字段,value字段
        Map<Integer, String> studentNameMap =
                list.stream().collect(Collectors.toMap(Student::getId, Student::getName, (key1, key2) -> key2));
        System.out.println("List转map key字段,value字段: " + studentNameMap);

        // 转map并分组
        Map<Integer, List<Student>> studentGroupMap = list.stream().collect(Collectors.groupingBy(Student::getId));
        System.out.println("分组转map " + studentGroupMap);
        
        // 过滤
        List<Student> list = list.stream().filter(st-> st.getAge() == 10&& st.getName().equals("张三")).collect(Collectors.toList());
        
        // 判断是否存在
        List<StdArchEntity> list = stdArchMapper.select(fill(new StdArchSelectQuery()));
        if (!list.stream().anyMatch(StdArch -> !StdArch.getId().equals(query.getStdArchId()))) {
	    throw new BusinessException(ResultCode.PARAM_VALID_ERROR, "请设置体系");
        }
    }

    @Data
    static class Student {
        private int id;

        private String name;

        private int age;

        public Student(int id, String name, int age) {
            this.age = age;
            this.name = name;
            this.id = id;
        }
    }
}