1、拥有自定义对象 MyUser
1 @Data2 public classMyUser {3 privateString userName;4 privateString passWord;5 }
2、编写自定义去重方法实现
/*** 根据list中对象某些字段去重
*@paramlist 需要去重的list
*@return返回去重后的list*/
private static List removeDuplicateOutputField(Listlist) {
Set set = new TreeSet<>(new Comparator() {
@Overridepublic intcompare(MyUser myUser, MyUser myUserNew) {int compareToResult = 1;//==0表示重复
if(StringUtils.equals(myUser.getUserName(), myUserNew.getUserName()) &&StringUtils.equals(myUser.getPassWord(), myUserNew.getPassWord())) {
compareToResult= 0;
}returncompareToResult;
}
});
set.addAll(list);return new ArrayList<>(set);
}
注意:其中StringUtils.equals() 传入两个比较对象对应的字段,
比如想要加入userName 字段去重 就要加入 如下条件即可, 想要添加几个字段自行添加即可
StringUtils.equals(myUser.getUserName(), myUserNew.getUserName()) 也可以 使用
myUser.getAge().equals(myUserNew.getAge()) 自行测试决定
3、测试结果
@Testpublic voiddistinctMyUser(){
List list1 = new ArrayList<>();
MyUser user1= newMyUser();
user1.setUserName("zhangsan");
user1.setPassWord("1234567");
list1.add(user1);
MyUser user2= newMyUser();
user2.setUserName("zhangsan");
user2.setPassWord("123456");
list1.add(user2);
MyUser user3= newMyUser();
user3.setUserName("lisi");
user3.setPassWord("123456");
list1.add(user3);
MyUser user4= newMyUser();
user4.setUserName("lisi");
user4.setPassWord("123456");
list1.add(user4);for(MyUser b: list1) {
System.out.println("去重前:"+b.toString());
}//去重
list1 =removeDuplicateOutputField(list1);for(MyUser b: list1) {
System.out.println("去重后:"+b.toString());
}
}
运行结果如下,达到预期,根据自己想要的字段进行list集合去重操作。
二、List 自定义对象,根据某一列去重,利用lambad 来实现
@Testpublic voiddistinctList() {
AdviceInfo adviceInfo= newAdviceInfo();
adviceInfo.setHospId(8888L);
adviceInfo.setSex("女");
adviceInfo.setAge(22);
AdviceInfo adviceInfo2= newAdviceInfo();
adviceInfo2.setHospId(8888L);
adviceInfo2.setSex("男");
adviceInfo2.setAge(22);
ArrayList adviceInfos =Lists.newArrayList();
adviceInfos.add(adviceInfo);
adviceInfos.add(adviceInfo2);
adviceInfos.stream().filter(distinctByKey(e->e.getHospId()))
.collect(Collectors.toList())
.forEach(adviceInfo1->System.out.println(adviceInfo1.getSex()));
}public static Predicate distinctByKey(Function super T, Object>keyExtractor) {
Map map = new ConcurrentHashMap<>();return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
运行结果: