list.stream去重
时间: 2023-09-14 21:06:20 浏览: 61
使用 `Stream` 对一个 `List` 进行去重可以通过以下几种方式实现:
1. 使用 `distinct()` 方法:`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]
```
2. 使用 `collect()` 方法和 `toSet()` 收集器:`toSet()` 收集器会自动去重,可以将 `Stream` 中的元素收集到一个 `Set` 集合中,然后再转换为 `List`。示例代码如下:
```java
List<Integer> list = Arrays.asList(1, 2, 3, 2, 4, 3, 5);
List<Integer> distinctList = list.stream()
.collect(Collectors.toSet())
.stream()
.collect(Collectors.toList());
System.out.println(distinctList); // 输出: [1, 2, 3, 4, 5]
```
3. 使用 `collect()` 方法和自定义的收集器:如果想要自定义去重的逻辑,可以使用自定义的收集器来实现。示例代码如下:
```java
List<Integer> list = Arrays.asList(1, 2, 3, 2, 4, 3, 5);
List<Integer> distinctList = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingInt(o -> o))),
ArrayList::new
));
System.out.println(distinctList); // 输出: [1, 2, 3, 4, 5]
```
以上是几种常见的使用 `Stream` 去重的方式,根据具体的需求选择适合的方法即可。