Convert List to Map using JavaStream

Sometimes the blog content will change. The first blog is the latest, and other blog addresses may not be synchronized. Check it carefully.https://blog.zysicyj.top

First blog address

Series article address


Methods are available to convert List to Map using Java Stream Collectors.toMap(). toMap()The method accepts two parameters, the first parameter is a function used to extract the key of the Map, and the second parameter is a function used to extract the value of the Map. Here is an example:

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;
    }
}

In the above example, we have a Personclass that represents person information, including name and age. We List<Person>convert one to one Map<String, Integer>with name as key and age as value. Use Person::getNameas key extraction function, Person::getAgeas value extraction function. Finally, we print the results.

This article is published by mdnice multi-platform

Guess you like

Origin blog.csdn.net/njpkhuan/article/details/132753380