Python 官方文档:入门教程 => 点击学习
目录java8根据某一属性过滤去重根据list某一属性去重过滤StudentExamState=0的数据过滤ExamRoomStudentCount=0的数据Java8 stream
最近小编刚接触到java8特性,在不知道有java8特性的时候,一个for循环套一个for循环,自从接触大java8,为自己省了很多事,节省了很多代码量.
//根据id去重
examRoomModelLists = examRoomModelLists.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
// 利用 TreeSet 的排序去重构造函数来达到去重元素的目的
// 根据firstName去重
() -> new TreeSet<>(Comparator.comparing(ExamRoomModel::getId))), ArrayList::new));
em.setNoLoginExamineeCount((examinee.stream().map(ExamineeEntity::getStudentExamState).filter(x ->
x == 0).collect(Collectors.toList())).size());
}
List<ExamRoomModel> filterList = examRoomModelLists.stream().filter(ExamRoomModel ->
!Objects.equals(ExamRoomModel.getExamRoomStudentCount(), 0)).collect(Collectors.toList());
是不是很方便,换成以前过滤去重不知道要写多少横代码,现在一行解决.
public class Java8StreamTest {
public static class Book{
private String id;
private String name;
public Book(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Book{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
@Test
public void testUnique(){
List<Book> books = Lists.newArrayList(new Book("1","1"),new Book("2","2"),new Book("3","3"),new Book("2","2"));
//使用TreeSet去重
List<Book> unique1 = books.stream().collect(
collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId()))),
ArrayList::new));
System.out.println(unique1);
//使用map去重
List<Book> unique2 = books.stream()
.filter(distinctByKey(o -> o.getId()))
.collect(Collectors.toList());
System.out.println(unique2);
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
System.out.println("这个函数将应用到每一个item");
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
首先我们有一个对象属性如下
@Data
public class Person {
private String id;
private String name;
private String sex;
}
我们根据属性name来去重,去重代码如下
List<Person> persons = new ArrayList();
//赋值初始化过程省略
List<Person> uniqueByName = persons.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);
根据name,sex两个属性去重
List<Person> persons = new ArrayList();
//赋值初始化过程省略
List<Person> uniqueByNameAndSex = persons.stream().collect(
Collectors. collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: java8根据某一属性过滤去重的实例
本文链接: https://lsjlt.com/news/148062.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0