其他分享
首页 > 其他分享> > List<>根据多个元素去重

List<>根据多个元素去重

作者:互联网

Students students = new Students("李四1","20","男","123456789978654","1010","四川省");
Students students3 = new Students("张三1","21","女","258741369741","1010","重庆市");
Students students1 = new Students("李四2","20","男","123456789978654","1010","四川省");
Students students2 = new Students("张三2","21","女","258741369741","1010","重庆市");
Students students4 = new Students("王麻子","35","女","369856311785","2020","甘肃省");

List<Students> studentsList = new ArrayList<>();
studentsList.add(students);
studentsList.add(students1);
studentsList.add(students2);
studentsList.add(students3);
studentsList.add(students4);
System.out.println(JSON.toJSONString(studentsList));

/**
 * 方法一,根据idNo和idType去重
 */
String idN="";
String idT="";
Iterator iterator = studentsList.listIterator();
while (iterator.hasNext()){
    Students stu = (Students) iterator.next();
    if(idN.equals(stu.getIdNo()) && idT.equals(stu.getIdType())){
        iterator.remove();
    }else{
        idN=stu.getIdNo();
        idT=stu.getIdType();
    }
}
System.out.println(JSON.toJSONString(studentsList));

/**
 * 方法二
 * 根据stram方法去重
 * 根据idNo和idType去重
 */
List<Students> studentsList1 = studentsList.stream().collect(Collectors.collectingAndThen(
        Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(o->o.getIdNo()+";"+o.getIdType()))),ArrayList::new));

System.out.println(JSON.toJSONString(studentsList1));

标签:studentsList,iterator,多个,Students,元素,List,stu,add,new
来源: https://blog.csdn.net/qq_41458352/article/details/120103919