java 8 stream的一些实用操作

引入依赖

 		
        
            org.projectlombok
            lombok
            1.18.12
        
        
        
            junit
            junit
            4.13
        

定义一个测试类 Student


@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    private String name;

    private int id;
    
    private int age;
    // 年级
    private int grade;

}

定义一个测试以前的数据录入方法

  List<Student> students = null;
    @Before
    public void before(){
        Student student1 = new Student("张三", 1, 15, 5);
        Student student2 = new Student("李四", 2, 17, 6);
        Student student3 = new Student("王五", 3, 14, 5);
        students= Arrays.asList(student1, student2, student3);
    }

stream filter

 @org.junit.Test
    public void testFilter() {
        String name = "张三";
        students.stream().forEach(student -> System.out.println(student));
        System.out.println("--------------------------------------");
        students.stream().filter(student -> name.equals(student.getName())).forEach(student -> System.out.println(student));
    }

输出结果


Student(name=张三, id=1, age=15, grade=5)
Student(name=李四, id=2, age=17, grade=6)
Student(name=王五, id=3, age=14, grade=5)
--------------------------------------
Student(name=张三, id=1, age=15, grade=5)

map 操作

 @org.junit.Test
    public void testMap() {
        students.stream().forEach(System.out::println);
        System.out.println("--------------------------------------");
        students.stream().map(Student::getName).forEach(System.out::println);
    }

输出结果

Student(name=张三, id=1, age=15, grade=5)
Student(name=李四, id=2, age=17, grade=6)
Student(name=王五, id=3, age=14, grade=5)
--------------------------------------
张三
李四
王五

stream 对象转map操作

  @org.junit.Test
    public void testConvertMap() {
        Map<Integer, String> stuMap = students.stream().collect(Collectors.toMap(Student::getId, Student::getName));
        stuMap.forEach((id, name) -> System.out.println(String.format("学生id = %d , 学生姓名name = %s ", id, name)));
    }

输出结果

学生id = 1 , 学生姓名name = 张三 
学生id = 2 , 学生姓名name = 李四 
学生id = 3 , 学生姓名name = 王五 

stream group分组操作

  @org.junit.Test
    public void testGroup() {
        Map<Integer, List<Student>> stuMap = students.stream().collect(Collectors.groupingBy(Student::getGrade));
        stuMap.forEach((grade,stus)-> System.out.println(String.format("年级是 = %d",grade)+"\n所属年级下的学生基本信息: "+stus+"\n---------------"));
    }

输出结果

年级是 = 5
所属年级下的学生基本信息: [Student(name=张三, id=1, age=15, grade=5), Student(name=王五, id=3, age=14, grade=5)]
---------------
年级是 = 6
所属年级下的学生基本信息: [Student(name=李四, id=2, age=17, grade=6)]
---------------

你可能感兴趣的:(java 8 stream的一些实用操作)