Java集合去重

在日常工作中,我们时常会遇到需要对数据进行遍历去重的操作,笔者便将自己所熟知的几种方法分享给大家。

首先模拟一个实体类,并创建一个main方法调用。

public static void main(String[] args) {
        List<User> list = new ArrayList(4);
        list.add(new User("张三","杭州"));
        list.add(new User("李四","上海"));
        list.add(new User("王五","深圳"));
        list.add(new User("赵六","深圳"));

}
public class User{
        private String name;
        private String city;

        public User(String name, String city) {
            this.name = name;
            this.city = city;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getCity() {
            return city;
        }
        public void setCity(String city) {
            this.city = city;
        }
    }
1.双重循环比较
 思路:创建一个新的不重复列表 每次遍历元素都和之前存放的元素进行比较,若重复则移除,遍历一次后再放入。这也是初学者们最先运用到的一种方法。
public List duplicateRemovalByCircle(List<User> list){
       
        List newList = new ArrayList();
        for (int i = 0;i < list.size();i++){
            for (int j = 0;j < i;j++){
                if(list.get(i).getCity().equals(list.get(j).getCity())){
                    newList.remove(list.get(j).getCity());
                }
            }
            newList.add(list.get(i).getCity());
        }
        return list;
    }
2.使用Set集合
思路:Set是元素不可重复的集合,遍历列表直接将元素放入Set集合即可完成去重,或者直接使用Set转换成List的方法
拓展:查看源码可知,HashSet的底层是HashMap,而HashSet的Add方法也就是调用了HashMap的put方法,Set的元素作为Map中的key,Object实例作为值。
public List duplicateRemovalBySet(List<User> list){
        Set set = new HashSet();
        list.addAll(set);
        for(int i = 0;i < list.size();i++){
            set.add(list.get(i).getCity());
        }
        List newlist = new ArrayList();
        newlist.addAll(set);
        return newlist;
    }
3.使用Java8的新特性 stream进行去重
思路:使用流操作集合,高效易懂,并且拓展性强。
    public List duplicateRemovalByStream(List<User> list){
        List newList = new ArrayList();
        newList = list.stream().map(User::getCity).distinct().collect(Collectors.toList());
        return newList;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值