Java Stream: List to Map with Object Values
To use Stream to convert a List to a Map where the Map's values are objects, you can utilize the collect() method of the Stream along with Collectors.toMap(). This approach enables you to transform your List into a Map while preserving the object details.
Let's consider a scenario where you have a List of objects, each containing id and name properties. The goal is to create a Map where the keys are the id values, and the corresponding values are the objects themselves.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> personList = List.of(
new Person(1, 'Alice'),
new Person(2, 'Bob'),
new Person(3, 'Charlie')
);
// Convert the List to a Map using Stream
Map<Integer, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, person -> person));
// Print the Map's contents
personMap.forEach((id, person) -> {
System.out.println('ID: ' + id + ', Person: ' + person);
});
}
}
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;
}
@Override
public String toString() {
return 'Person{' +
'id=' + id +
', name=' + name + ''' +
'}';
}
}
In the example above, we define a Person class with id and name attributes. A List containing Person objects is created. We then employ the collect() method of the Stream along with Collectors.toMap() to transform the List into a Map, where the keys are the id values and the values are the Person objects themselves.
Finally, we use forEach() to iterate over the Map's entries and print each key-value pair. Running this code will produce the following output:
ID: 1, Person: Person{id=1, name='Alice'}
ID: 2, Person: Person{id=2, name='Bob'}
ID: 3, Person: Person{id=3, name='Charlie'}
This method provides an efficient and concise way to convert a List of objects to a Map using Java Stream, allowing you to easily manipulate and organize your data.
原文地址: https://www.cveoy.top/t/topic/qlSj 著作权归作者所有。请勿转载和采集!