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.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap