通过id对java list集合进行分组之后返回到同一个list集合中
时间: 2024-05-01 18:23:45 浏览: 147
java实现把一个List集合拆分成多个的操作
可以使用Java 8中的Stream API来对List集合进行分组,然后将分组后的元素添加到同一个List集合中。下面是一个示例代码:
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GroupList {
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person(1, "Alice"));
persons.add(new Person(2, "Bob"));
persons.add(new Person(3, "Charlie"));
persons.add(new Person(4, "David"));
persons.add(new Person(5, "Eva"));
persons.add(new Person(6, "Frank"));
persons.add(new Person(7, "George"));
persons.add(new Person(8, "Henry"));
persons.add(new Person(9, "Ivy"));
persons.add(new Person(10, "Jack"));
// 将Person对象按照id进行分组
Map<Integer, List<Person>> groupedMap = persons.stream().collect(Collectors.groupingBy(Person::getId));
// 将分组后的元素添加到同一个List集合中
List<Person> result = new ArrayList<>();
groupedMap.values().forEach(result::addAll);
System.out.println(result);
}
}
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{id=1, name='Alice'}, Person{id=2, name='Bob'}, Person{id=3, name='Charlie'}, Person{id=4, name='David'}, Person{id=5, name='Eva'}, Person{id=6, name='Frank'}, Person{id=7, name='George'}, Person{id=8, name='Henry'}, Person{id=9, name='Ivy'}, Person{id=10, name='Jack'}]
```
阅读全文