2

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());
    }
Tor
  • 47
  • 11
  • 3
    It's possible you'll find a library that offers this as a utility method. But in general, you can't do better than this. – Oliver Charlesworth Sep 01 '14 at 19:31
  • 2
    Also, `ArrayList` is *not* an `ArrayList`... – Oliver Charlesworth Sep 01 '14 at 19:32
  • What are you going to do with the stringList? Depending on that, you might just not do the conversion separately at all and use toString() only where you really need the string. – PMF Sep 01 '14 at 19:33
  • @OliCharlesworth Agreed, these are *not* equivalent; my interpretation (as, no doubt) yours is that the OP just wants to go from any array list and get the string representation for each element. – therealrootuser Sep 01 '14 at 19:33
  • @PMF I'm going to hand over an ArrayList to an adapter in Android, so I think I needed to do this conversion ahead or override things in the adapter. – Tor Sep 02 '14 at 03:59

3 Answers3

3

Using Java 8:

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

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

ajb
  • 31,309
  • 3
  • 58
  • 84
  • I tested it and it works! Interesting! Unfortunately I'm still on Java 7 and Android. – Tor Sep 02 '14 at 03:54
  • @Tor Android hasn't even made it up to Java 7 yet. :( Still some features missing. With luck, Android will implement Java 8 sometime before the rest of the Java world has gotten up to Java 12 ... – ajb Sep 02 '14 at 05:37
2

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!

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
0

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);
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249