Several ways to convert java object list into map according to a certain attribute using stream

A List can be converted to a Map using the Stream API in Java 8, with a property as key or value. Here is some sample code:

Convert List to Map, the key is a property, and the value is the object itself

List<Person> personList = ... // 假设这是一个Person对象列表
Map<String, Person> personMap = personList.stream()
        .collect(Collectors.toMap(Person::getName, Function.identity()));

In this example, the list of Person objects is converted into a Map, where the key is the name property of the Person object and the value is the Person object itself.

Convert List to Map, the key is the object itself, and the value is an attribute


List<Person> personList = ... // 假设这是一个Person对象列表
Map<Person, String> personMap = personList.stream()
        .collect(Collectors.toMap(Function.identity(), Person::getAddress));

In this example, the list of Person objects is converted into a Map where the key is the Person object itself and the value is the address property of the Person object.

Convert a List to a Map with a key as a property and a value as another property

List<Person> personList = ... // 假设这是一个Person对象列表
Map<String, String> personMap = personList.stream()
        .collect(Collectors.toMap(Person::getName, Person::getAddress));

In this example, the list of Person objects is converted into a Map, where the key is the name property of the Person object and the value is the address property of the Person object.

Whichever way you use it, you can use Java 8's Stream API to convert a List to a Map with a property as key or value. It should be noted that when converting List to Map, the key must be unique, otherwise an exception will be thrown.

Guess you like

Origin blog.csdn.net/qq_16607641/article/details/130711355