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

2021/12/1 17:06:51

本文主要是介绍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 stream操作collectingAndThen根据对象的属性去重的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程