How to convert a list of objects to a list of strings in Java

To convert a list of objects to a list of strings in Java, you can use the Streams API map() method. Suppose we have the following User.java class that stores user information.

public class User {
    private String name;
    private String profession;
    private int age;

    public User(String name, String profession, int age) {
        this.name = name;
        this.profession = profession;
        this.age = age;
    }

    // getters and setters, equals(), toString() .... (omitted for brevity)
}

The following example demonstrates how you can convert a list of User objects into a list of strings using Java 8 streams:

// Create a list of users
List<User> users = List.of(
        new User("John Doe", "Engineer", 23),
        new User("Alex Mike", "Doctor", 43),
        new User("Jovan Lee", "Lawyer", 34)
);

// Convert list of users to list of strings
List<String> list = users.stream()
        .map(User::toString)
        .collect(Collectors.toList());

// Print list of strings
list.forEach(System.out::println);

// User{name='John Doe', profession='Engineer', age=23}
// User{name='Alex Mike', profession='Doctor', age=43}
// User{name='Jovan Lee', profession='Lawyer', age=34}

To convert a list of User objects to a list of name values, you can do the following:

List<String> list = users.stream()
        .map(User::getName)
        .collect(Collectors.toList());

list.forEach(System.out::println);

// John Doe
// Alex Mike
// Jovan Lee

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.