Stream流---根据对象中的某个属性值实现去重

User类

package com.gao.JDK8.Stream流;

import lombok.Data;

import java.util.Date;

@Data
public class User {

    private String name;
    private String pass;
    private Date time;

    public User(String name, String pass, Date time) {
        this.name = name;
        this.pass = pass;
        this.time = time;
    }
}

 

 实现-去重

package com.gao.JDK8.Stream流;

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

public class G01 {
    public static void main(String[] args) {
        //Stream按对象某属性去重的方案
        User user1 = new User("","123456",new Date());
        User user11 = new User("","123456",new Date());

        User user2 = new User("", "123456", new Date());
        User user22 = new User("", "123456", new Date());

        User user3 = new User("g", "123", null);


        List<User> userList = Arrays.asList(user1,user11,user2,user22, user3);
        ArrayList<User> collect1 = userList.stream().collect(
                // 将集合先放到 treeSet 集合然后将他们转换成数组
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getName())))
                        , ArrayList::new)
        );

        collect1.forEach(System.out::println);
} }

 

实现--结果:

 

 
posted @ 2022-11-07 21:36  向大海  阅读(2384)  评论(0编辑  收藏  举报