Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ArrayList of objects to ArrayList of this objects String names in Java

I have an ArrayList of User objects. Now I need the ArrayList of these user's names only. Is there a way to use toString() on entire ArrayList and convert it to ArrayList of String names rather than doing this in for loop? I have also overridden toString in User class so it returns user's name, and I have tried ArrayList <String> names = usersList.toString() but it didn't work.

like image 856
Mike55 Avatar asked Dec 10 '22 14:12

Mike55


1 Answers

You can do this using the Google Collections API:

List<User> userList = ...;
List<String> nameList = Lists.transform(userList, new Function<User, String>() {
   public String apply(User from) {
      return from.toString(); // or even from.getName();
   }
});

The library has been renamed to Guava.


With Java 8, using streams and method references you can now achieve the same thing even without using Guava:

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

class User {

    private String name;

    public User() {
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class App {
    public static void main(String[] args) {
        List<User> users = new ArrayList<>(Arrays.asList(
                new User("Alan Turing"),
                new User("John von Neumann"),
                new User("Edsger W Dijkstra")
        ));

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

        System.out.println(names);
    }
}
like image 51
Behrang Avatar answered Dec 12 '22 05:12

Behrang