JAVA中List对象去除重复值的方法

  JAVA中List对象去除重复值,大致分为两种情况,一种是List<String>、List<Integer>这类,直接根据List中的值进行去重,另一种是List<User>这种,List中存的是javabean对象,需要根据List中对象的某个值或某几个值进行比较去重。方法如下:

 

一、List<String>、List<Integer>对象去重复值。

这种情况的话,处理起来比较简单,通过JDK1.8新特性stream的distinct方法,可以直接处理。

1     List<String> list1 = Arrays.asList("a", "b", "c", "a", new String("c"));
2     list1.stream().distinct().forEach(System.out::println);
3 
4     List<Integer> list2 = Arrays.asList(1, 2, 3, 1, new Integer(2));
5     list2.stream().distinct().forEach(System.out::println);

 

二、List<User>对象去重复值。

这种的话,不能直接比较List中的对象,需要重写bean对象的equals和hashCode方法,然后通过放入Set集合来自动去重,具体例子如下。

对象实体:

复制代码
 1 @Data
 2 @AllArgsConstructor
 3 public class User {
 4     private String id;
 5     private String name;
 6     private int age;
 7 
 8     public boolean equals(Object obj) {
 9         User u = (User) obj;
10         return name.equals(u.name);
11     }
12 
13     public int hashCode() {
14         String in = name;
15         return in.hashCode();
16     }
17 }
复制代码

以上例子中就是通过比较姓名相同,即认为对象相等。

 

1     List<User> userList = new ArrayList<>();
2     userList.add(new User("1", "peter", 18));
3     userList.add(new User("2", "stark", 25));
4     userList.add(new User("3", "peter", 22));
5     
6     Set<User> userSet = new HashSet<>(userList);
7     List<User> list = new ArrayList<>(userSet);
8     list.forEach(System.out::println);

通过将List放入Set进行自动去重(即使用到上面的equals与hashCode方法),然后重新放回List中即可。

 

posted @   PC君  阅读(46923)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2017-05-27 JAVA中文件与Byte数组相互转换的方法
2017-05-27 HttpClient方式调用接口的实例

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示