一、去除List中重複的String
List<String> unique = list.stream().distinct().collect(Collectors.toList());
二、List中對象去重
public class Person {
private Long id;
private String name;
public Person(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
// 根據id去重
List<Person> unique = persons.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)
);