JAVA8 - 使用stream api进行list集合指定字段去重

背景

有一个list,实体包含多个字段,当其中两个字段值均相同时,就认为list中的这两条记录是一样的

去重

java8中有一个collectingAndThen可以根据多个字段去重

依据姓名和年龄去重,当姓名和年龄相同时,认为这两个实体相同

class FlightTicketInfo {

    private String orderNumber;

    private String userName;

    private String age;

    public FlightTicketInfo(String orderNumber, String userName, String age) {
        this.orderNumber = orderNumber;
        this.userName = userName;
        this.age = age;
    }

    @Override
    public String toString() {
        return "FlightTicketInfo{" +
                "orderNumber='" + orderNumber + '\'' +
                ", userName='" + userName + '\'' +
                ", age='" + age + '\'' +
                '}';
    }

    public String getOrderNumber() {
        return orderNumber;
    }

    public String getUserName() {
        return userName;
    }

    public String getAge() {
        return age;
    }
}

    @Test
    public void testList(){
        List<FlightTicketInfo> infoList = new ArrayList<>();
        infoList.add(new FlightTicketInfo("11111", "xiaoming", "22"));
        infoList.add(new FlightTicketInfo("22222", "xiaoming", "22"));
        infoList.add(new FlightTicketInfo("33333", "xiaoming", "23"));
        infoList.add(new FlightTicketInfo("11111", "xiaoming", "22"));
        infoList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(f -> f.getUserName()+f.getAge()))), ArrayList::new))
                .forEach(System.out::println);
    }

原文链接:https://blog.csdn.net/qq_28988969/article/details/81119587

posted @ 2020-12-15 16:28  uzxin  阅读(3901)  评论(0编辑  收藏  举报