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

在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。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理