如何实现java8 list按照元素的某个字段去重
list 按照元素的某个字段去重
1
2
3
4
5
6
7
|
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer age; private String name; } |
测试数据
1
2
3
4
5
|
List<Student> studentList = Lists.newArrayList(); studentList.add( new Student( 28 , "river" )); studentList.add( new Student( 12 , "lucy" )); studentList.add( new Student( 33 , "frank" )); studentList.add( new Student( 33 , "lucy" )); |
java8 通过tree set 去重
1
2
3
4
5
6
7
8
|
List<Student> studentDistinctList = studentList.stream() .collect(Collectors.collectingAndThen (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> t.getName()))), ArrayList:: new ) ); System.out.println( new Gson().toJson(studentDistinctList)); |
扩展distinct 方法去重
1
2
3
|
List<Student> studentDistinct2List = studentList.stream().filter(StreamUtil.distinctByKey(t->t.getName())) .collect(Collectors.toList()); System.out.println( new Gson().toJson(studentDistinct2List)); |
工具类
1
2
3
4
5
6
7
8
9
10
11
12
|
public class StreamUtil { /** * https://stackoverflow.com/questions/23699371/java-8-distinct-by-property * @param keyExtractor * @param <T> * @return */ public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Set<Object> seen = ConcurrentHashMap.newKeySet(); return t -> seen.add(keyExtractor.apply(t)); } } |
我是个双鱼座的小王子,沉浸在自己的代码世界里,去探索这未知的世界,希望遇到更多的小伙伴一起前行!