提交 49cf2bb1 编写于 作者: M Mars Liu

group by

上级 0cb742f2
{
"node_id": "java-4cc01469b31d42ac80854c4024c1b15a",
"keywords": [],
"children": [],
"export": [],
"title": "操作分组的元素"
}
\ No newline at end of file
{
"node_id": "java-873636226f0e44ad9269f2a13fe2adb9",
"keywords": [],
"children": [],
"export": [],
"title": "多级分组"
}
\ No newline at end of file
{
"node_id": "java-1223956aa7ae47a9a2e517dc23c3f371",
"keywords": [],
"children": [],
"export": [],
"title": "按子组收集数据"
}
\ No newline at end of file
# 分组
已知类型
```java
public class Employee{
int id;
String name;
String department;
}
```
`List<Employee> employee` 中的员工信息按部门分组,其中不正确的是:
## 答案
```java
// List<Employee> employee = ...;
Map<String, Object> result = employee.stream().collect(toMap(Employee::getDepartment, Function.identity()));
```
## 选项
### 标准方法
```java
// List<Employee> employee = ...;
Map<String, List<Employee>> result = employee.stream().collect(groupingBy(Employee::getDepartment));
```
### 朴素方法
```java
// List<Employee> employee = ...;
Map<String, List<Employee>> result = new HashMap<>();
for(var emp: employee){
var list = result.getOrDefault(emp.department, new ArrayList<>());
list.add(emp);
}
```
### 朴素方法
```java
Map<String, List<Employee>> result = new HashMap<>();
for(int index=0; index < employee.size(); index++){
var emp = employee.get(index);
var list = result.getOrDefault(emp.department, new ArrayList<>());
list.add(emp);
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册