public static voidmain(String[] args) {
List list1 = new ArrayList<>();
User user01= newUser();
user01.setId(1L);
user01.setName("Bell");
list1.add(user01);
User user02= newUser();
user02.setId(2L);
user02.setName("Jack");
list1.add(user02);
List list2 = new ArrayList<>();
User user03= newUser();
user03.setId(2L);
user03.setName("Tom");
list2.add(user03);
User user04= newUser();
user04.setId(3L);
user04.setName("Tao");
list2.add(user04);
Map target = new HashMap();if (CollectionUtils.isNotEmpty(list1) &&CollectionUtils.isNotEmpty(list2)) {
//把list1放入Map target中,key取用户idfor(User tempUser : list1) {
target.put(tempUser.getId(), tempUser);
}for(User user2 : list2) {
Long userId=user2.getId();if(target.containsKey(userId)) {
User temp=target.get(userId);//用户id重复,以list2中的用户姓名为准
temp.setName(user2.getName());
target.put(userId, temp);
}else{
target.put(userId, user2);
}
}
}
List list = new ArrayList(target.values());
System.out.println("对象数据类型的list合并并且去重结果====>:" +list);
}/*** 基础数据类型的list合并并且去重,业务场景比较简单*/
private static voidintList() {
List list1 = new ArrayList();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
List list2 = new ArrayList();
list2.add(1);
list2.add(4);
list2.add(7);
list2.add(10);
List listAll = new ArrayList();
listAll.addAll(list1);
listAll.addAll(list2);//去重
listAll = new ArrayList(new LinkedHashSet<>(listAll));
System.out.println("方法一:" +listAll);
list1.removeAll(list2);
list1.addAll(list2);
System.out.println("方法二:" +list1);
}