使用JavaStream将List转为Map

有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top

首发博客地址

系列文章地址


使用Java Stream将List转换为Map可以使用Collectors.toMap()方法。toMap()方法接受两个参数,第一个参数是用于提取Map的键的函数,第二个参数是用于提取Map的值的函数。下面是一个示例:

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

public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Alice"25),
                new Person("Bob"30),
                new Person("Charlie"35)
        );

        Map<String, Integer> ageByName = people.stream()
                .collect(Collectors.toMap(Person::getName, Person::getAge));

        System.out.println(ageByName);
    }
}

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

在上面的示例中,我们有一个Person类表示人员信息,包含姓名和年龄。我们将一个List<Person>转换为一个Map<String, Integer>,其中姓名作为键,年龄作为值。使用Person::getName作为键提取函数,Person::getAge作为值提取函数。最后,我们将结果打印出来。

本文由 mdnice 多平台发布

猜你喜欢

转载自blog.csdn.net/njpkhuan/article/details/132753380