public class TestRemoveDuplicateData { public static void main(String[] args) { List<SingleDog> lists = new ArrayList<SingleDog>(); 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); System.out.println("去重前----------------------"); for(SingleDog sd :lists){ System.out.println(sd.toString()); } lists = TestRemoveDuplicateData.Removedup(lists); System.out.println("去重后----------------------"); for(SingleDog sd :lists){ System.out.println(sd.toString()); } } public static List<SingleDog> Removedup(List<SingleDog> list){ Map<String,SingleDog> hash = new HashMap<>(); // 通过hashMap的key不能重复,达到去重的目的 for(SingleDog aa :list){ hash.put(aa.getName(),aa); } List<SingleDog> newList = new ArrayList<SingleDog>() ; for(Map.Entry<String,SingleDog> set : hash.entrySet()){ newList.add(set.getValue()); } return newList; } }
测试结果:
去重前----------------------
SingleDog{age=18, sex='男', name='张三'}
SingleDog{age=23, sex='男', name='李四'}
SingleDog{age=23, sex='男', name='李四'}
去重后----------------------
SingleDog{age=23, sex='男', name='李四'}
SingleDog{age=18, sex='男', name='张三'}