Java Stream Convert List of Objects to List of Strings

Example:
package org.code2care.java.examples;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Person {

    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class Example {
    public static void main(String[] args) {

        List<Person> personList = Arrays.asList(
                new Person("Mike"),
                new Person("Sam"),
                new Person("Alex"),
                new Person("Stacy")
        );


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

        System.out.println("Result: " + namesList);
    }
}

In the above example, we converted a list of Person object to list of Strings using the map() function.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!