Java Streams: Extract List Object Values

You can use the map method of Stream to retrieve a certain value from objects in a List. For example, if you have a List where each Person object has a name attribute, and you want to retrieve the name attribute of all Person objects, you can do so like this:

List<Person> personList = new ArrayList<>();
// 填充personList

List<String> names = personList.stream()
                               .map(Person::getName)
                               .collect(Collectors.toList());

In this example, we use the map method of Stream to map each Person object to its name property, and finally collect all name properties into a List.

bannerAds