Java中,List<Demo>, Demo { id: long, name: string, address: string, type: string },如何对list 按 type 进行分组?
// 按 type 进行分组
Map<String, List<Demo>> groupedByType = demoList.stream().collect(Collectors.groupingBy(Demo::getType));
import java.util.*;
import java.util.stream.Collectors;
class Demo {
long id;
String name;
String address;
String type;
public Demo(long id, String name, String address, String type) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
}
public String getType() {
return type;
}
@Override
public String toString() {
return "Demo{" +
"id=" + id +
", name='" + name + '\'' +
", address='" + address + '\'' +
", type='" + type + '\'' +
'}';
}
}
public class Main {
public static void main(String[] args) {
List<Demo> demoList = Arrays.asList(
new Demo(1, "Alice", "Address1", "TypeA"),
new Demo(2, "Bob", "Address2", "TypeB"),
new Demo(3, "Charlie", "Address3", "TypeA"),
new Demo(4, "David", "Address4", "TypeB"),
new Demo(5, "Eve", "Address5", "TypeC")
);
Map<String, List<Demo>> groupedByType = demoList.stream()
.collect(Collectors.groupingBy(Demo::getType));
groupedByType.forEach((type, demos) -> {
System.out.println("Type: " + type);
demos.forEach(System.out::println);
});
}
}
可以增加一个Idea Live Template:
Map<$key$, $obj$> $map$ = $list$.stream().collect(Collectors.toMap($obj$::$get$, item -> item));$END$
<template name="lm" value="Map<$key$, $obj$> $map$ = $list$.stream().collect(Collectors.toMap($obj$::$get$, item -> item));$END$" description="List Object convert to Map Object" toReformat="false" toShortenFQNames="true">
<variable name="key" expression="" defaultValue=""Long"" alwaysStopAt="true" />
<variable name="obj" expression="" defaultValue=""Object"" alwaysStopAt="true" />
<variable name="map" expression="" defaultValue=""map"" alwaysStopAt="true" />
<variable name="list" expression="" defaultValue=""list"" alwaysStopAt="true" />
<variable name="get" expression="" defaultValue="" alwaysStopAt="true" />
<context>
<option name="JAVA_STATEMENT" value="true" />
</context>
</template>