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.
I have an ArrayList of User objects. Now I need the ArrayList of these
Share
The
Object#toString()returns aString, not anArrayList. 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 😉With Java 8, you can use lambda expressions, streams, and method references to simplify your code.
The following
can then be shortened to like
By the way, you can also put the
forin a single line:It may however not be directly understandable for starters.