java8怎么把list集合通过map分组处理重复key
时间: 2023-11-27 19:52:47 浏览: 41
可以使用 `Collectors.groupingBy` 方法来进行分组操作。示例如下:
假设有一个 `Person` 类,包含 `id` 和 `name` 属性:
```
public class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
```
现在有一个包含多个 `Person` 对象的 `List` 集合,我们要按照 `id` 属性进行分组处理:
```
List<Person> personList = new ArrayList<>();
personList.add(new Person(1, "Tom"));
personList.add(new Person(2, "Jerry"));
personList.add(new Person(1, "Mike"));
personList.add(new Person(3, "John"));
Map<Integer, List<Person>> result = personList.stream()
.collect(Collectors.groupingBy(Person::getId));
```
以上代码将 `personList` 中的 `Person` 对象按照 `id` 属性进行分组,得到一个 `Map<Integer, List<Person>>` 对象,其中键为 `id`,值为包含相同 `id` 的 `Person` 对象的 `List`。
执行完上述代码后,`result` 的值为:
```
{
1=[Person{id=1, name='Tom'}, Person{id=1, name='Mike'}],
2=[Person{id=2, name='Jerry'}],
3=[Person{id=3, name='John'}]
}
```
可以看到,`id` 为 1 的 `Person` 对象被分到了同一个 `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_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)