stream -根据指定字段去重
前言
很久之前的需求了,这里随手记录下
万一哪天要用,不用到处百度
根据指定(一个或多个)字段去重list
import lombok.Data;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class test {
public static void main(String[] args) {
List<Person> ps = new ArrayList<>();
ps.add(new Person(11, "tom"));
ps.add(new Person(11, "张三"));
ps.add(new Person(12, "tom"));
ps.add(new Person(11, "tom"));
//根据name进行去重
List<Person> list = ps.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);
System.out.println("根据name进行去重");
list.forEach(System.out::println);
System.out.println();
//根据name与age进行去重
List<Person> list1 = ps.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(p -> p.getName() + ";" + p.getAge()))), ArrayList::new)
);
System.out.println("根据name 和 age 进行去重");
list1.forEach(System.out::println);
}
}
@Data
class Person {
String name;
int age;
Person(int age, String name) {
this.name = name;
this.age = age;
}
}
执行结果:
根据name进行去重
Person(name=tom, age=11)
Person(name=张三, age=11)
根据name 和 age 进行去重
Person(name=tom, age=11)
Person(name=tom, age=12)
Person(name=张三, age=11)
总结
如果我是个小说作者…那么我不会水字数。
原谅我直接贴代码