Transforming List of Objects to List of Strings in Java

Views: 99   

We often need to convert a List of Objects to List of Strings where that String can be a particular element from the Object. For Example List of Names from List of User Objects.
This program shows you how to transform in Java using map.

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

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

        List<User> users = new ArrayList<>();
        users.add(new User("foo", 20));
        users.add(new User("bar", 30));

        List<String> userNames = users.stream().map(u -> u.name).collect(Collectors.toList());
        System.out.println(userNames);
    }
}

class User {
    String name;
    int age;

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

Output

[foo, bar]
On By