简体   繁体   中英

How to populate an ArrayList<String> from ArrayList<Object>

Is there a smarter way to populate this list of strings by getting the collection of gameList and converting the Game objects to strings?

ArrayList<Game> gameList = getAllGames();
ArrayList<String> stringList = new ArrayList<String>();
    for (Game game : gameList) {
        stringList.add(game.toString());
    }

Using Java 8:

ArrayList<String> stringList = gameList.stream().map(Object::toString).collect(Collectors.toCollection(ArrayList::new));

(Note: I haven't yet tested this.)

You could use new Java 8 lambdas and streams :

List<String> stringList = getAllGames().stream()
    .map(game -> game.toString())
    .collect(Collectors.toList());

Look at that, wonderful!

Well, I would prefer to use the List interface, that way you can swap the List implementation out without changing caller code. Also, you could use the diamond operator . Finally, you could construct the new ArrayList with an optimal initial capacity -

List<Game> gameList = getAllGames();
List<String> stringList = new ArrayList<>(gameList.size());
for (Game game : gameList) {
    stringList.add(game.toString());
}

Or a new helper method like,

public static List<String> getStringList(List<?> in) {
    List<String> al = new ArrayList<>(in != null ? in.size() : 0);
    for (Object obj : in) {
        al.add(obj.toString());
    }
    return al;
}

then

List<String> stringList = getStringList(gameList);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM