对list去重,通过两次增强for循环

public static void main(String[] args) {
        List lists = new ArrayList();
        SingleDog a = new SingleDog();
        a.setAge(18);
        a.setName("张三");
        a.setSex("男");
        lists.add(a);
        SingleDog b = new SingleDog();
        b.setAge(23);
        b.setName("李四");
        b.setSex("男");
        lists.add(b);
        SingleDog c = new SingleDog();
        c.setAge(23);
        c.setName("李四");
        c.setSex("男");
        lists.add(c);

        SingleDog d = new SingleDog();
        d.setAge(33);
        d.setName("王五");
        d.setSex("男");
        lists.add(d);
        System.out.println("去重前----------------------");
        for (SingleDog sd : lists) {
            System.out.println(sd.toString());
        }
        List newList2 =   getSingleDogs(lists);
        System.out.println("去重后----------------------");
        for (SingleDog sd : newList2) {
            System.out.println(sd.toString());
        }

    }

    public static List getSingleDogs(List list) {
        // 创建一个新的list对象
        List newList = new ArrayList();
        boolean flag = false;
        for (SingleDog oldSD : list) {
            for (SingleDog newSD : newList) {
                if (newSD.getName().equals(oldSD.getName())) {
                    flag = true;
                }else {
                    flag =false;
                }
            }
            if (!flag) {
                newList.add(oldSD);
            }
        }

        return newList;
    }




package com.september;

/**
 * Created by cdm on 2018/9/24
 */
public class SingleDog {

    int age;

    String name;

    String sex;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "SingleDog{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

测试结果:

去重前----------------------
SingleDog{age=18, name='张三', sex='男'}
SingleDog{age=23, name='李四', sex='男'}
SingleDog{age=23, name='李四', sex='男'}
SingleDog{age=33, name='王五', sex='男'}
去重后----------------------
SingleDog{age=18, name='张三', sex='男'}
SingleDog{age=23, name='李四', sex='男'}
SingleDog{age=33, name='王五', sex='男'}

你可能感兴趣的:(java)