java将集合某个字段转为新集合并且去重
时间: 2024-03-19 20:43:56 浏览: 55
假设有一个Person类,其中有一个字段为name,现在有一个List<Person>集合,你想将其中的name字段提取出来,转为一个新的List<String>集合,并且需要去重,可以使用如下代码实现:
```java
List<Person> personList = new ArrayList<>();
// ... 向personList中添加元素
// 使用stream操作将name字段提取出来转为新的List集合,并去重
List<String> nameList = personList.stream()
.map(Person::getName)
.distinct()
.collect(Collectors.toList());
```
其中,stream()方法将集合转为流,map()方法将Person对象映射为其name字段,distinct()方法去重,最后使用collect()方法将结果收集为List集合。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)