编程语言
首页 > 编程语言> > Java stream操作collectingAndThen根据对象的属性去重

Java stream操作collectingAndThen根据对象的属性去重

作者:互联网

创建实体对象user

/**
 * 用户
 *
 * @author sun
 * @date 2021/08/19
 */
@Data
public class User {

    private Integer id;
    
    private String name;

    private String password;

    private Integer age;

    private String address;
	
	public User() {
    }
    
	public User(Integer id, String name, String password, Integer age, String address) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
        this.address = address;
    }
    
}

新建一个List集合添加数据,然后根据name去重生成一个新的集合


```java
public class Deme1 {

    @Test
    public void streamTest1() {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "aaa", "111", 20, "杭州"));
        userList.add(new User(2, "bbb", "222", 21, "上海"));
        userList.add(new User(3, "ccc", "333", 22, "广州"));
        userList.add(new User(4, "ddd", "444", 23, "深圳"));
        userList.add(new User(5, "aaa", "555", 24, "北京"));
        List<User> result = userList.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(checklistResultDto -> checklistResultDto.getName()))), ArrayList::new));
        result.forEach(user -> System.out.println("user = " + user));
    }
}




标签:Java,String,stream,collectingAndThen,private,userList,add,User,new
来源: https://blog.csdn.net/Redolently/article/details/121657714