JAVA Stream List 转 Map

在Java编程中,有时候我们需要将一个List转换为Map,其中List的某个属性作为Map的key,List中的对象作为Map的value。这个操作可以使用Java8中的Stream API来实现,让代码更加简洁和高效。

Stream API 简介

Java 8引入了Stream API,它提供了一种新的抽象,可以让开发人员以一种更为函数式的方式处理集合数据。Stream API可以让我们更加简洁地进行集合操作,如过滤、映射、排序等。

List 转 Map

假设我们有一个实体类Person,包含idname两个属性,现在我们有一个List<Person>,需要将其转换为Map,其中id作为key,Person对象作为value。

下面是一个简单的Person类的定义:

public class Person {
    private int id;
    private String name;

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // getters and setters
}

接下来,我们创建一个List<Person>示例数据:

List<Person> personList = new ArrayList<>();
personList.add(new Person(1, "Alice"));
personList.add(new Person(2, "Bob"));
personList.add(new Person(3, "Charlie"));

现在我们利用Stream API将List转换为Map:

Map<Integer, Person> personMap = personList.stream()
        .collect(Collectors.toMap(Person::getId, Function.identity()));

在上面的代码中,我们使用stream()方法将List转换为Stream,然后使用collect(Collectors.toMap())将Stream转换为Map。Person::getId表示以id属性作为Map的key,Function.identity()表示以对象本身作为Map的value。

完整代码示例

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(1, "Alice"));
        personList.add(new Person(2, "Bob"));
        personList.add(new Person(3, "Charlie"));

        Map<Integer, Person> personMap = personList.stream()
                .collect(Collectors.toMap(Person::getId, Function.identity()));

        System.out.println(personMap);
    }

    public static 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 + '\'' +
                    '}';
        }
    }
}

Sequence Diagram

下面是List转Map的序列图示例:

sequenceDiagram
    participant List
    participant Stream
    participant Map

    List ->> Stream: 转换为Stream
    Stream ->> Map: 转换为Map

总结

使用Stream API将List转换为Map的操作,可以让代码更加简洁和高效。通过这种方式,我们可以更方便地对集合数据进行处理,提高代码的可读性和维护性。希望本文对你有所帮助,谢谢阅读!