关于java:Java-8使用Stream-API将List中的对象元素遍历出来并放入Map中

7次阅读

共计 1032 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 8 中,能够应用 Stream API 将 List 中的对象元素遍历进去并放入 Map 中。上面是一种常见的形式:

假如有一个蕴含 Person 对象的 List,每个 Person 对象都有惟一的 ID 和对应的姓名。咱们想要将这些 Person 对象遍历进去,并依据 ID 作为 Key,姓名作为 Value,放入一个 Map 中。

首先,确保 Person 类具备 getId() 和 getName() 办法,用于获取 ID 和姓名。

而后,应用 Stream 的 collect() 办法,联合 Collectors.toMap() 办法,能够将 List 中的对象元素依照指定的 Key 和 Value 映射关系收集到 Map 中。

以下是示例代码:

import java.util.*;
import java.util.stream.Collectors;

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;}
}
public class Main {public static void main(String[] args) {
        List<Person> personList = Arrays.asList(new Person(1, "John"),
                new Person(2, "Alice"),
                new Person(3, "Bob")
        );

        Map<Integer, String> idToNameMap = personList.stream()
                .collect(Collectors.toMap(Person::getId, Person::getName));

        System.out.println(idToNameMap);
    }
}

运行以上代码,输入后果为:

{1=John, 2=Alice, 3=Bob}

在这个示例中,咱们应用了 Stream 的 collect() 办法,将 List 中的 Person 对象遍历进去并依照指定的 Key 和 Value 映射关系收集到 Map 中。应用 Person::getId 作为 Key 提取器,Person::getName 作为 Value 提取器。最终失去一个蕴含 ID 和姓名映射关系的 Map。

你能够依据具体的需要批改代码,替换 Person 类的属性和提取器办法,以及要放入 Map 中的 Key 和 Value。

正文完
 0