Java8利用Stream处理集合,开发中常见的用法

首先初始化一个测试集合

 private static List<Student> students=new ArrayList<>();

    static {
        students.add(new Student(1,"aa",18,"beijing"));
        students.add(new Student(2,"bb",19,"shanghai"));
        students.add(new Student(3,"cc",16,"jiangxi"));
        students.add(new Student(4,"dd",17,"hebei"));
        students.add(new Student(5,"ee",11,"tianjing"));
        students.add(new Student(6,"aa",11,"tianjing"));
    }
 /**
     * 过滤
     */
    @Test
    public void test0(){
        List<Student> beijing = students.stream().filter((e) -> e.getAddress().equals("beijing"))
                .collect(Collectors.toList());
        System.out.println(beijing);
    }

    /**
     * 去重以及limit个数
     */
    @Test
    public void test(){
        students.stream().map(Student::getAddress).distinct().limit(1).forEach(System.out::println);
    }


    /**
     * 提取基础元素中的某一个属性,转成list
     */
    @Test
    public void test1(){
        List<String> names = students.stream().map((Student::getName))
                .collect(Collectors.toList());
        System.out.println("names:"+names);
    }
    /**
     * 集合中按某一属性进行自定义排序后转成list
     */
    @Test
    public void test2(){
        students.stream().sorted((o1,o2)->{
                             if(o1.getAge()==o2.getAge()){
                                 return o1.getName().compareTo(o2.getName());
                             }else{
                                 return -(o1.getAge()-o2.getAge());
                             }
                         }).forEach(System.out::println);
    }
    @Test
    public void test3(){
        List<Integer> collect = students.stream().map(Student::getId).collect(Collectors.toList());
        System.out.println(collect);
    }
    /**
     * 进行entity转dto
     */
    @Test
    public void test4(){
        CollectTest collectTest = new CollectTest();
        List<StudentDTO> dtos=students.stream().map(collectTest::entityToDto)
                .collect(Collectors.toList());
        System.out.println(dtos);
    }
    /**
     * list转成map
     */
    @Test
    public void test5(){
        Map<Integer, String> map = students.stream().collect(Collectors.toMap(Student::getId, Student::getName));
        System.out.println(map);
    }

    public  StudentDTO entityToDto(Student student){
        return  new StudentDTO(student.getId(), student.getName());
    }


}

# Java  

评论

公众号:mumuser

企鹅群:932154986

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×