List集合去重
1. 去除List中重复的String
方法一:通过LinkedHashSet有序Set集合去重
方法二:通过stream流的distinct方法去重
@Test
public void test1(){
//方法1,通过LinkedHashSet有序Set集合,来将List中的重复元素去除,去除后清除原本List的元素,将set集合添加到List中。
List<Object> stringList = new ArrayList<Object>(Arrays.asList(1,2,3,3,5,6,7,7));
Set<Object> set = new LinkedHashSet<>();
set.addAll(stringList);
stringList.clear();
stringList.addAll(set);
stringList.stream().forEach(a -> System.out.println(a));
//方法2 使用stream流的方法去重(distinct)并通过collect收集对象再重新组合成list集合
List<String> stringList2 = new ArrayList<String>(Arrays.asList("haha","hehe","haha"));
List<String> list = stringList2.stream().distinct().collect(Collectors.toList());
System.out.println(list);
}
2. 去除List中重复的对象
方法一:通过stream流结合contains方法去重 方法二:通过stream流distinct方法去重。
//List中对象去重
@Test
public void test2(){
//方法1
// 通过forEach遍历persons集合中的对象
// 通过contains方法判断创建新的集合中是否有persons集合中的对象,如果没有再添加对象。
Person p1 = new Person(1l, "jack");
Person p2 = new Person(3l, "jack chou");
Person p3 = new Person(2l, "tom");
Person p4 = new Person(4l, "hanson");
Person p5 = new Person(5l, "胶布虫");
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5, p5, p1, p2, p2);
List<Person> personList = new ArrayList<>();
// 去重
persons.stream().forEach(
p -> {
if (!personList.contains(p)) {
personList.add(p);
}
}
);
System.out.println(personList);
//方法2,通过Stream流,先去重,通过collect收集对象重新组成List集合。
List<Person> list = persons.stream().distinct().collect(Collectors.toList());
System.out.println(list);
}
3. 根据对象属性去重
通过Comparator比较器,对比对象属性进行去重
//根据对象属性去重(根据Person对象的id去重)
@Test
public void test3(){
//方法一 通过Comparator比较器,比较对象属性,相同就返回0,达到过滤的目的。
Person p1 = new Person(1l, "jack");
Person p2 = new Person(3l, "jack chou");
Person p3 = new Person(4l, "chou");
List<Person> persons = Arrays.asList(p1,p2,p3,p1,p2,p3);
Set<Person> personSet = new TreeSet<>((o1, o2) -> o1.getId().compareTo(o2.getId()));
personSet.addAll(persons);
ArrayList<Person> list = new ArrayList<>(personSet);
System.out.println(list);
}