如何實現java8 list按照元素的某個字段去重
2019-06-28 14:37良人與我 Java教程
這篇文章主要介紹了如何實現java8 list按照元素的某個字段去重,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,,需要的朋友可以參考下
list 按照元素的某個字段去重
測試數據
1 | List<Student> studentList = Lists.newArrayList(); |
2 | studentList.add( new Student( 28 , "river" )); |
3 | studentList.add( new Student( 12 , "lucy" )); |
4 | studentList.add( new Student( 33 , "frank" )); |
5 | studentList.add( new Student( 33 , "lucy" )); |
java8 通過tree set 去重
1 | List<Student> studentDistinctList = studentList.stream() |
2 | .collect(Collectors.collectingAndThen |
3 | (Collectors.toCollection(() -> |
4 | new TreeSet<>(Comparator.comparing(t -> t.getName()))), |
8 | System.out.println( new Gson().toJson(studentDistinctList)); |
擴展distinct 方法去重
1 | List<Student> studentDistinct2List = studentList.stream().filter(StreamUtil.distinctByKey(t->t.getName())) |
2 | .collect(Collectors.toList()); |
3 | System.out.println( new Gson().toJson(studentDistinct2List)); |
工具類
01 | public class StreamUtil { |
08 | public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { |
09 | Set<Object> seen = ConcurrentHashMap.newKeySet(); |
10 | return t -> seen.add(keyExtractor.apply(t)); |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。