2019-06-19 13:25:24 2252瀏覽
今天千鋒扣丁學堂Java培訓老師給大家分享一篇關(guān)于如何實現(xiàn)Java8中l(wèi)ist按照元素的某個字段去重的詳細介紹,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,下面我們一起來看一下吧。
@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"));
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));
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)); } }
【關(guān)注微信公眾號獲取更多學習資料】 【掃碼進入JavaEE/微服務VIP免費公開課】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>