list.stream().distinct
时间: 2023-09-24 21:05:05 浏览: 52
引用<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [list.stream distinct列表去重](https://blog.csdn.net/sinat_27115575/article/details/102456083)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
相关问题
list.stream去重
使用 `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` 去重的方式,根据具体的需求选择适合的方法即可。
list.stream().distinct()和使用set去重区别
list.stream().distinct() 和使用 set 去重的区别在于操作的对象不同。
list.stream().distinct() 是使用 Java 8 中的 Stream API 对 List 中的元素进行去重操作,返回一个去重后的 Stream。而使用 set 去重则是将 List 转化为 Set,去除重复元素,并将结果存储在 Set 中。
在实现上,使用 list.stream().distinct() 可以保留数据的原有顺序,但是需要消耗更多的计算资源。而使用 set 去重则不会保留原有顺序,但在去重效果和计算效率上优于 list.stream().distinct()。
另外,使用 list.stream().distinct() 时需要通过 equals() 和 hashCode() 方法来判断元素是否相同,而使用 set 去重则只需要重写元素的 equals() 和 hashCode() 即可。