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.
views:
175answers:
4
A:
public ArrayList< String > toStringList( Collection< MyObject > objectList )
{
ArrayList< String > stringList = new ArrayList< String >();
for( MyObject myobj : objectList ) {
stringList.add( myobj.toString() );
}
return stringList;
}
...
ArrayList< String > myStringList = toStringList( objectList );
There. One line, and you can reuse it with whatever collection of objects you have in the future.
Shawn D.
2010-08-14 14:31:08
I mentioned I was wondering if it is possible without using for loop, something like stringList.addAll(objectList.toString() )
Mike55
2010-08-14 14:34:39
@Mike55 Why avoid the for loop? Even if you write this in such a way where you don't use a for-loop, by using a library call like Guava, at some point some piece of code must still visit every element in the list to transform it
matt b
2010-08-14 15:08:05
+4
A:
The Object#toString()
returns a String
, not an ArrayList
. That's your problem. You really need to loop over it. There's absolutely no reason for an aversion against looping. Just hide it away in some utility method if the code is bothering you somehow ;)
You can also wait for Java 7 being released and then use the powers of closures.
The following
List<User> users = getItSomehow();
List<String> names = new ArrayList<String>();
for (User user : users) {
names.add(user.getName());
}
can then be shortened to like
List<User> users = getItSomehow();
List<String> names = users.map({ User user => user.getName() });
By the way, you can also put the for
in a single line:
for (User user : users) names.add(user.getName());
It may however not be directly understandable for starters.
BalusC
2010-08-14 14:31:16
+6
A:
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.
Bytecode Ninja
2010-08-14 14:39:00
Can be shortened to `List<String> nameList = Lists.transform(userList, Functions.toStringFunction());`, as long as you stick to `toString` (instead of the suggested `getName`).
Willi
2010-08-14 15:35:37