Shortcut for list->stream->map()->list

You could statically import Collectors.* and then use the mapping(Function, Collector) method, like this:

myList.stream().collect(mapping(T::getName, toList()));

Where T::getName is a method reference and T is the Type of the elements in the List. Using this is more readable and also almost identical to writing: el -> el.name


You could create a static helper method that does all the work:

public static <FROM, TO> List<TO> convert(List<FROM> from, Function<FROM, TO> function) {
    return from.stream().map(function).collect(Collectors.toList());
}

All you have to do is provide your list and any mapping function:

List<YourClass> yourList = ...;
Function<YourClass, String> func = YourClass::getName;
List<String> converted = convert(yourList, func);

Or even more concise:

List<String> converted = convert(yourList, YourClass::getName);

I think that you should stick to what you have already got. Why?

  1. It’s already a one-liner. No real point in trying to squeeze it down further.
  2. It’s idiomatic. Java developers are used to read conversions like yours, and if it’s all over the place in your code, programmers that read your code will be even more used to it. Even wrapping it in a method, like @QBrute suggested, even though a nice idea, risks harming readability because readers are not used to the wrapping method.

Remember: Brevity is not a goal. Clarity is. The two often go hand in hand, but not always, and my feeling is they may not in your case.

Reservation: My style and taste is in favour of the method reference that @Aomine uses, but it is a matter of taste. Use it if you find it clearer, not just because it’s a few chars shorter.


There's no shorter way to do this using streams.

you could import import static java.util.stream.Collectors.*; and then use toList as follows to shorten the code a little bit but apart from this. The below is as compact as it gets using streams:

myList.stream().map(el -> el.name).collect(toList());

You could also use a method reference

myList.stream().map(T::getName).collect(toList()); 

where T is the name of type that contains name although this is not guaranteed to be shorter depending on how long the type name is but does provide better readability which is very important.

Ultimately, as said this is as compact as it gets.