list集合去重

开发过程中,有些数据查询出来后,需要通过代码再处理一遍,通常sql查询出来的数据,list集合中是对象,根据一些值来判断是否重复

示例

public class Student {

    private String name;
    private String code;
    private String id;
    private String time;

    
}
package com.test2;

import java.util.ArrayList;
import java.util.List;

public class Test1 {

    public static void main(String[] args) {

        /**
         *
         * 利用list去重
         * */

        Student tom = new Student("tom", "002", "1", "1997");
        Student tom2 = new Student("tom", "002", "1", "1998");
        Student tom3 = new Student("tom", "002", "1", "1999");
        Student tom4 = new Student("tom4", "002", "1", "2000");
        Student tom5 = new Student("tom4", "002", "1", "2001");
        Student jack = new Student("jack", "001", "1", "1997");
        Student jack2 = new Student("jack", "001", "1", "1998");
        Student marry = new Student("marry", "003", "1", "1997");
        Student marry2 = new Student("marry", "003", "1", "1998");

        List<Student> list = new ArrayList();
        list.add(tom);
        list.add(tom2);
        list.add(tom3);
        list.add(tom4);
        list.add(tom5);
        list.add(jack);
        list.add(jack2);
        list.add(marry);
        list.add(marry2);

        System.out.println("原list"+list);


        for (int i =0 ;i<list.size();i++){
            for(int j=i+1;j<list.size();j++){
                if(list.get(i).getCode().equals(list.get(j).getCode()) &&
                list.get(i).getId().equals(list.get(j).getId())&&
                list.get(i).getName().equals(list.get(j).getName())){
                    /**
                     * 每一次删除都需要重置,因为list的长度会变,需要重头开始
                     * */
                    list.remove(i);
                    i = 0;
                    j = 0;
                }
            }
        }

        System.out.println("去重后list"+list);


    }
}

 去重后的结果,这个例子是根据code,name,id去判断,可以根据实际情况去修改判断条件

 原list[Student{name='tom', code='002', id='1', time='1997'}, Student{name='tom', code='002', id='1', time='1998'}, Student{name='tom', code='002', id='1', time='1999'}, Student{name='tom4', code='002', id='1', time='2000'}, Student{name='tom4', code='002', id='1', time='2001'}, Student{name='jack', code='001', id='1', time='1997'}, Student{name='jack', code='001', id='1', time='1998'}, Student{name='marry', code='003', id='1', time='1997'}, Student{name='marry', code='003', id='1', time='1998'}]


去重后list[Student{name='tom', code='002', id='1', time='1999'}, Student{name='tom4', code='002', id='1', time='2001'}, Student{name='jack', code='001', id='1', time='1998'}, Student{name='marry', code='003', id='1', time='1998'}]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值