Set<Book> list = new HashSet<>();
{
list.add(new Book("Core Java", 200));
list.add(new Book("Core Java", 200));
list.add(new Book("Learning Freemarker", 150));
list.add(new Book("Spring MVC", 200));
list.add(new Book("Hibernate", 300));
}
System.out.println(list.size());
list.stream().filter(distinctByKey(b -> b.getPrice()))
.forEach(b -> System.out.println(b.getName() + "," + b.getPrice()));
//存在重复数据的问题,这里使用stream流的衍生功能,去除一个对象中的部分元素的重复如下:
ArrayList<Book> collect = list.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(
Book::getPrice))), ArrayList::new));
System.out.println(collect.size());
//多个字段或者多个条件去重
ArrayList<Book> collect1 = list.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(p->p.getName() + ";" + p.getPrice()))), ArrayList::new));
Stream<String> streamBuilder =
Stream.<String>builder().add("a").add("b").add("c").build();
streamBuilder.forEach(System.out::println);
stream 去重
最新推荐文章于 2024-04-16 14:44:33 发布