Person类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @descrition
* @since 2020-05-19 11:33
*/
@AllArgsConstructor
@Data
@NoArgsConstructor
public class Person {
private String name;
private String sex;
}
去重操作
import java.util.*;
import java.util.stream.Collectors;
/**
* @description
* @since 2020-06-17 09:50
*/
public class Test0617 {
private static List<String> strList = new ArrayList<String>() {{
add("zhangsan");
add("lisi");
add("wangwu");
add("wangwu");
}};
private static List<Person> objList = new ArrayList<Person>() {{
add(new Person("zhangsan", "male"));
add(new Person("lisi", "male"));
add(new Person("wangwu", "female"));
}};
public static void main(String[] args) {
// 元素为String的list去重
List<String> strResult = strList.stream().distinct().collect(Collectors.toList());
strResult.forEach(System.out::println);
// 元素为Person的list根据性别去重
List<Person> result = objList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(p -> p.getSex()))
),
ArrayList::new)
);
result.forEach(System.out::println);
}
}
console输出
zhangsan
lisi
wangwu
Person(name=wangwu, sex=female)
Person(name=zhangsan, sex=male)