根据对象的属性去重(TreeSet、map,多个属性)

1:根据对象的属性去重(通过TreeSet、map等方式,支持多个属性去重)

package com.itsource.enjoy.util;

import com.itsource.enjoy.domain.entity.Student;

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

/**
 * 根据集合中的某属性去重
 */
public class ListUtils {
    public static void main(String[] args) {

        //模拟数据
        List<Student> students = new ArrayList<Student>(){{
            add(new Student().setAge(27).setName("帅哥").setSex(true));
            add(new Student().setAge(19).setName("校花").setSex(false));
            add(new Student().setAge(18).setName("校花").setSex(false));
        }};

        //方式一:根据name去重  用 collectingAndThen
        List<Student> list1 = students.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
        //[Student(name=帅哥, age=27, sex=true, birthDay=null, scores=null, status=null), Student(name=校花, age=19, sex=false, birthDay=null, scores=null, status=null)]

        //扩展:根据多个字段去重
        List<Student> unique = students.stream().collect(
                Collectors. collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(student -> student.getName() + ";" + student.getAge()))), ArrayList::new));
        //[Student(name=帅哥, age=27, sex=true, birthDay=null, scores=null, status=null), Student(name=校花, age=18, sex=false, birthDay=null, scores=null, status=null), Student(name=校花, age=19, sex=false, birthDay=null, scores=null, status=null)]


        //方式二:根据name去重   转化为map然后再转回list
        Map<String, Student> studentMap = students.stream().collect(Collectors.toMap(Student::getName, Function.identity(), (k1, k2) -> k1));
        List<Student> list2 = studentMap.values().stream().collect(Collectors.toList());
        //[Student(name=帅哥, age=27, sex=true, birthDay=null, scores=null, status=null), Student(name=校花, age=19, sex=false, birthDay=null, scores=null, status=null)]



    }
}
package com.itsource.enjoy.domain.entity;

import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Date;
import java.util.List;

/**
 * 学生类
 */
@Accessors(chain = true)
@Data
public class Student {

    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 性别
     */
    private Boolean sex;

    /**
     * 生日
     */
    private Date birthDay;


    /**
     * 成绩集合
     */
    private List<Score> scores;

    /**
     * 状态类型
     */
    private String status;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值