您好,登錄后才能下訂單哦!
list 按照元素的某個字段去重
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer age; private String name; }
測試數(shù)據(jù)
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)); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。