Junior — Middle
How can you obtain a stream of elements from a collection as a Map using the Stream API?
sobes.tech AI
Answer from AI
In Java Stream API, you can convert a collection to a Map using the Collectors.toMap() method. You need to specify functions that extract the key and value from the stream elements.
Example: there is a list of Person objects, and you want to get a Map where the key is the ID, and the value is the name.
import java.util.*;
import java.util.stream.*;
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 Example {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob"),
new Person(3, "Charlie")
);
Map<Integer, String> idToName = people.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(idToName);
}
}
The result will be a Map with keys as IDs and values as names.