根据某个字段去重并返回集合 使用stream 流 并返回多个字段
时间: 2023-08-12 19:27:04 浏览: 141
要根据某个字段去重并返回多个字段,可以使用Java 8中的Stream API。假设我们有一个Person类,其中包含id、name和age三个字段,现在我们要根据id去重并返回name和age字段,可以按照以下方式进行操作:
```java
List<Person> personList = new ArrayList<>(); // 假设已经有了Person对象列表
List<Person> distinctPersonList = personList.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))),
ArrayList::new
));
List<String> nameList = distinctPersonList.stream()
.map(Person::getName)
.collect(Collectors.toList());
List<Integer> ageList = distinctPersonList.stream()
.map(Person::getAge)
.collect(Collectors.toList());
```
上述代码中,我们首先使用toCollection()方法将Stream中的元素插入到TreeSet集合中,并按照Person对象的id字段进行去重。然后,我们将TreeSet集合转换为ArrayList集合,最终得到去重后的Person对象列表。
接着,我们可以分别使用map()方法将Person对象的name和age字段提取出来,并使用toList()方法将它们转换为List集合。
需要注意的是,由于我们使用了TreeSet集合进行去重,因此Person对象需要实现Comparable接口或者提供一个指定比较器的构造函数,以便TreeSet可以正确比较并去重。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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)
![](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)