Sobes.tech
Junior — Middle

How can a list of elements be transformed into a Map structure?

sobes.tech AI

Answer from AI

In Java, to convert a list of elements into a Map structure, you can use the Stream API and the Collectors.toMap() method.

Example: there is a list of objects, and you want to create a Map where the key is some property of the object, and the value is either the object itself or another property.

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

class Person {
    String id;
    String name;
    Person(String id, String name) {
        this.id = id;
        this.name = name;
    }
    public String getId() { return id; }
    public String getName() { return name; }
}

List<Person> people = Arrays.asList(
    new Person("1", "Alice"),
    new Person("2", "Bob")
);

Map<String, String> idToName = people.stream()
    .collect(Collectors.toMap(Person::getId, Person::getName));

System.out.println(idToName); // {1=Alice, 2=Bob}

If keys can repeat, you need to use the version of toMap that accepts a merge function.

How can a list of elements be transformed into a Map… - sobes.tech