java8 stream 属性去重
时间: 2023-11-08 15:04:36 浏览: 44
对于Java 8的Stream属性去重,你可以使用distinct()方法来实现。distinct()方法返回一个去重后的Stream,它根据元素的hashCode()和equals()方法来判断是否重复。
下面是一个示例代码,演示了如何在Stream中去重属性:
```java
List<Person> persons = Arrays.asList(
new Person("John", 25),
new Person("Alice", 30),
new Person("John", 25),
new Person("Bob", 35)
);
List<Person> distinctPersons = persons.stream()
.distinct()
.collect(Collectors.toList());
distinctPersons.forEach(System.out::println);
```
在这个例子中,Person类有name和age两个属性。使用distinct()方法可以去除相同的Person对象,保留唯一的对象。请确保Person类正确地实现了hashCode()和equals()方法。
相关问题
java8 stream 根据属性去重
可以使用 distinct() 方法,再利用参数为 Function 的 distinct() 方法,根据指定属性去重。例如:list.stream().distinct().collect(Collectors.toList()); 或者list.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList()); (需要自定义一个 distinctByKey 方法)
java通过stream流去重
Java通过Stream流去重有几种方式。一种是使用Stream的distinct()方法来去除重复元素。另一种是使用collectingAndThen()和toCollection()方法结合使用,先将元素放入TreeSet中去除重复,再转换为ArrayList。还可以使用filter()方法根据某个属性进行去重。
示例代码如下:
```
List<User> uniqueList = list.stream().distinct().collect(Collectors.toList());
List<User> uniqueList = list.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getName))),
ArrayList::new)
);
List<User> uniqueList = list.stream().filter(
distinctByKey(User::getName)
).collect(Collectors.toList());
// Helper method
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
```