欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java1.8对根据字段属性对集合去重处理和lambda过滤集合

程序员文章站 2022-06-07 13:14:28
...
package com.qiu.test;

import com.qiu.test.entity.Employee;
import com.qiu.test.tools.FilterEmployeeByAge;
import com.qiu.test.tools.MyEmployeeInterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {

    List<Employee> employees = Arrays.asList(
            new Employee("小李",20,222.23),
            new Employee("张三",8,3333.333),
            new Employee("张三",9,3333.333),
            new Employee("王五",60,4444.444),
            new Employee("马超",78,5555.555),
            new Employee("鲁班七号",8,6666.666)

    );


    // 获取年龄大于等于35的员工
    public List<Employee> filterEmployee(List<Employee> list){
        List<Employee> emp= new ArrayList<>();
        for (Employee e: list){
            if (e.getAge()>=35){
                emp.add(e);
            }
        }
        return  emp;
    }

    // 方式一、获取年龄大于35的员工信息
    public List<Employee> filterEmp(List<Employee> list, MyEmployeeInterface<Employee> map){
        List<Employee> e= new ArrayList<>();
        for (Employee employee: list){
            if (map.test(employee)){
                e.add(employee);
            }
        }
        return e;
    }
    // 测试方法一
    @Test
    public void test1(){
        List<Employee> list = filterEmp(this.employees, new FilterEmployeeByAge());
        for (Employee e: list){
            System.out.println(e);
        }
    }

    // 方法二、Lambda表达式获取年龄大于35的员工
    @Test
    public void test2(){
        List<Employee> employees = this.filterEmp(this.employees, (e) -> e.getAge() > 35);
        employees.forEach(System.out::println);
    }


    /**
    * 描述: streamAPI
    * @Date 2019/12/5 17:45
    */
    @Test
    public void contextLoads() {
        List<Employee> stream = this.employees.stream()
                .filter((e) -> e.getSalary() >= 1000)
                .limit(5)
               // .distinct() //distinct只能去掉只能去掉属性值完全相同的条目
                .collect(Collectors.toList());
        System.out.println("streamAPI"+stream);
    }

    // 根据指定字段对集合去重处理(张三重复)
    @Test
    public void test8(){
        List<Employee> distinctClass = employees.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSalary()))), ArrayList::new));
        distinctClass.forEach(System.out::println);
    }



}