java list 字段去重_如何实现java8 list按照元素的某个字段去重
list 按照元素的某個字段去重
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer age;
private String name;
}
測試數據
List 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 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 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
* @return
*/
public static Predicate distinctByKey(Function super T, ?> keyExtractor) {
Set seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
總結
以上是生活随笔為你收集整理的java list 字段去重_如何实现java8 list按照元素的某个字段去重的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: snipping截图快捷键(截图快捷键s
- 下一篇: 巫师三快捷键翻滚(巫师3快捷键大全)