Better way to convert an List<MyDataType> to List<String>

java

Solution

With Guava, there is a more functional approach:

return FluentIterable.from(allAccounts).transform(new Function<Account,String>(){
    public String apply(Account account){return account.getName();}
}).toImmutableList()

But that essentially does the same thing, of course.

BTW: the difference between this answer and RNJ's is that in my case the list will be created once, while in the other answer it's a live view. Both versions are valid, but for different scenarios.

Problem

I am wondering if there isn't a better way to convert whole `Lists` or `Collections` as the way I show in the following code example: ``` public static List<String> getAllNames(List<Account> allAccounts) { List<String> names = new ArrayList<String>(allAccounts.size()); for (Account account : allAccounts) { names.add(account.getName()); } return names; } ``` Every time I produce a `method` like this, I start thinking, isn't there a better way? My first thought would be to create maybe a solution with some `generics` and `reflections`, but this seems maybe a bit over sized and maybe a bit to slow when it comes to performance?

Original source