根据规则去掉List 对象数组中的重复元素
Posted z360519549
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据规则去掉List 对象数组中的重复元素相关的知识,希望对你有一定的参考价值。
package container.main; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.TreeSet; import container.bean.GxyJobEntity; public class RemoveSame public static void main(String[] args) List<GxyJobEntity> list = new ArrayList<>(); GxyJobEntity gxyJobEntity1 = new GxyJobEntity(); gxyJobEntity1.setUserId("user001"); gxyJobEntity1.setPlanId("plan001"); gxyJobEntity1.setStudentId("stu001"); GxyJobEntity gxyJobEntity2 = new GxyJobEntity(); gxyJobEntity2.setUserId("user002"); gxyJobEntity2.setPlanId("plan002"); gxyJobEntity2.setStudentId("stu002"); GxyJobEntity gxyJobEntity3 = new GxyJobEntity(); gxyJobEntity3.setUserId("user003"); gxyJobEntity3.setPlanId("plan001"); gxyJobEntity3.setStudentId("stu001"); list.add(gxyJobEntity1); list.add(gxyJobEntity2); list.add(gxyJobEntity3); List<GxyJobEntity> list1 = removeDuplicate(list); System.out.println(list); System.out.println(list1); private static List<GxyJobEntity> removeDuplicate(List<GxyJobEntity> list) Set<GxyJobEntity> set = new TreeSet<GxyJobEntity>(new Comparator<GxyJobEntity>() public int compare(GxyJobEntity a, GxyJobEntity b) System.out.println("a:" + a); System.out.println("b:" + b); // 字符串则按照asicc码升序排列 if ( a.getStudentId().equals(b.getStudentId()) && a.getPlanId().equals(b.getPlanId()) ) return 0; else return 1; ); System.out.println("set:" + set.size() + "-->" + set); set.addAll(list); System.out.println("set:" + set.size() + "-->" + set); return new ArrayList<GxyJobEntity>(set);
如果 对象 GxyJobEntity 中两个属性 studentId 和 planId 相等,则保留一个,去掉多余的。
输出:
set:0-->[]
a:GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user001]
b:GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user001]
a:GxyJobEntity [jobId=null, studentId=stu002, planId=plan002, userId=user002]
b:GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user001]
a:GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user003]
b:GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user001]
set:2-->[GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user001], GxyJobEntity [jobId=null, studentId=stu002, planId=plan002, userId=user002]]
[GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user001], GxyJobEntity [jobId=null, studentId=stu002, planId=plan002, userId=user002], GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user003]]
[GxyJobEntity [jobId=null, studentId=stu001, planId=plan001, userId=user001], GxyJobEntity [jobId=null, studentId=stu002, planId=plan002, userId=user002]]
以上是关于根据规则去掉List 对象数组中的重复元素的主要内容,如果未能解决你的问题,请参考以下文章