首页  编辑  

List对象按指定Key分组

Tags: /Java/   Date Created:
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")
        );

        // 按 type 进行分组
        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&lt;$key$, $obj$&gt; $map$ = $list$.stream().collect(Collectors.toMap($obj$::$get$, item -&gt; item));$END$" description="List Object convert to Map Object" toReformat="false" toShortenFQNames="true">
  <variable name="key" expression="" defaultValue="&quot;Long&quot;" alwaysStopAt="true" />
  <variable name="obj" expression="" defaultValue="&quot;Object&quot;" alwaysStopAt="true" />
  <variable name="map" expression="" defaultValue="&quot;map&quot;" alwaysStopAt="true" />
  <variable name="list" expression="" defaultValue="&quot;list&quot;" alwaysStopAt="true" />
  <variable name="get" expression="" defaultValue="" alwaysStopAt="true" />
  <context>
    <option name="JAVA_STATEMENT" value="true" />
  </context>
</template>