Java8 list.stream()常用方法

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

public class StreamTest {
    public static class Student{
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

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

        @Override
        public boolean equals(Object o) {
            if (o == null || getClass() != o.getClass()) return false;
            Student student = (Student) o;
            return age == student.age && Objects.equals(name, student.name);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, age);
        }
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("d");

        List<Student>  studentList = new ArrayList<>();
        Student s1 = new Student("Tom",15);
        Student s2 = new Student("Jack",16);
        Student s3 = new Student("David",17);
        Student s4 = new Student("David",17);
        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        studentList.add(s4);

        //筛选满足条件的元素
        list = list.stream().filter(s -> s.contains("a")).collect(Collectors.toList());
        studentList = studentList.stream().filter(s -> "Tom".equals(s.name)).collect(Collectors.toList());

        //元素映射转换,转换成大写
        list = list.stream().map(String::toUpperCase).collect(Collectors.toList());
        //元素映射转换,学生类转换成学生名字
        List<String> nameList = studentList.stream().map(Student::getName).collect(Collectors.toList());

        //去重
        list = list.stream().distinct().collect(Collectors.toList());
        //实体类去重,需重写equals
        studentList = studentList.stream().distinct().collect(Collectors.toList());

        //正序
        list = list.stream().sorted().collect(Collectors.toList());
        //倒序
        list = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

        //实体类的某个字段正序
        studentList = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
        //实体类的某个字段倒序
        studentList = studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());

        //分组
        Map<String,List<Student>> map = studentList.stream().collect(Collectors.groupingBy(Student::getName));

    }
}

 

posted on 2026-03-12 09:56  Neonuu  阅读(2)  评论(0)    收藏  举报