java中使用stream去重
时间: 2023-11-28 18:46:17 浏览: 34
Java中使用Stream去重可以通过使用distinct()方法来实现。具体实现方法如下:
```java
List<Integer> list = Arrays.asList(1, 2, 3, 2, 4, 3, 5);
List<Integer> distinctList = list.stream().distinct().collect(Collectors.toList());
System.out.println(distinctList); // 输出:[1, 2, 3, 4, 5]
```
上述代码中,我们首先创建了一个包含重复元素的List集合,然后使用stream()方法将其转换为Stream流,接着使用distinct()方法去重,最后使用collect()方法将去重后的元素收集到一个新的List集合中。
另外,如果我们需要根据对象的某个属性进行去重,可以使用自定义的方法来实现。具体实现方法如下:
```java
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;
}
List<UserAccount> list = new ArrayList<>();
UserAccount a = new UserAccount();
a.setId(57L);
UserAccount b = new UserAccount();
b.setId(57L);
UserAccount c = new UserAccount();
c.setId(56L);
list.add(a);
list.add(b);
list.add(c);
List<UserAccount> distinctList = list.stream().filter(distinctByKey(UserAccount::getId)).collect(Collectors.toList());
System.out.println(distinctList); // 输出:[UserAccount{id=57}, UserAccount{id=56}]
```
上述代码中,我们首先定义了一个自定义的方法distinctByKey(),该方法接收一个Function类型的参数keyExtractor,用于提取对象的某个属性作为去重的依据。在方法内部,我们使用ConcurrentHashMap来存储已经出现过的属性值,然后使用putIfAbsent()方法判断当前属性值是否已经存在于Map中,如果不存在则将其加入Map中,并返回true,否则返回false。最后,我们使用filter()方法和自定义的方法distinctByKey()来进行去重操作,最终使用collect()方法将去重后的元素收集到一个新的List集合中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)