final List<String> userIds = request.getUserIds();
final List<String> keys = userIds.stream().map(p -> {
return removePrefix(p);
}).collect(Collectors.toList());
Basically, every key in the list of userIds
contains a prefix "_user" which I want to remove for every key. So, I am invoking the removePrefix
function on each item of the list and storing that result in another list called "keys"
Yes it's fine although you could make it a little shorter and more readable with a method reference and a static import:
final List<String> keys = userIds.stream()
.map(this::removePrefix)
.collect(toList());
The answer of @assylias is nice, but if you are not worried about modifying the list in place (and that you are allowed to modify it via its ListIterator#set
method), a good alternative could be to use replaceAll
:
final List<String> userIds = request.getUserIds();
userIds.replaceAll(this::removePrefix);
replaceAll
works here because your function is a function from T to T (where T is String
in your case), so basically a UnaryOperator
, which is a Function<T,T>
.
If the mapping you wanted to apply would have been from a type T to U, then getting the list's stream and doing the mapping via the Stream#map
method (like you did) is the standard idiom.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.