如何实现java8 list按照元素的某个字段去重

网友投稿 316 2023-01-04


如何实现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));

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:web接口测试工具的实现(webserver接口测试工具)
下一篇:关键系统接口设计步骤(系统接口设计案例)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~