list 按照元素的某個字段去重
創新互聯公司是一家專業提供北塔企業網站建設,專注與做網站、成都網站制作、H5頁面制作、小程序制作等業務。10年已為北塔眾多企業、政府機構等服務。創新互聯專業網絡公司優惠進行中。
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer age; private String name; }
測試數據
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 去重
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 方法去重
List<Student> studentDistinct2List = studentList.stream().filter(StreamUtil.distinctByKey(t->t.getName())) .collect(Collectors.toList()); System.out.println(new Gson().toJson(studentDistinct2List));
工具類
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)); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創新互聯。
網頁名稱:如何實現java8list按照元素的某個字段去重
文章位置:http://www.2m8n56k.cn/article16/ihghgg.html
成都網站建設公司_創新互聯,為您提供建站公司、移動網站建設、企業建站、網站收錄、標簽優化、響應式網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:[email protected]。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯