[英]Is this correct usage of lambdas in Java 8?
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. 基本上,在列表中每个键
userIds
包含一个前缀“_user”,我想删除每一个关键。 So, I am invoking the removePrefix
function on each item of the list and storing that result in another list called "keys" 因此,我在列表的每个项目上调用
removePrefix
函数,并将结果存储在另一个称为“键”的列表中
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
: @assylias的答案很好,但是如果您不担心就地修改列表(并且可以通过
ListIterator#set
方法修改列表),那么一个很好的选择是使用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>
. replaceAll
在这里可以工作,因为您的函数是从T到T的函数(在您的情况下,T是String
),因此基本上是UnaryOperator
,它是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. 如果您想应用的映射是从T到U,那么获取列表的流并通过
Stream#map
方法(就像您所做的那样)进行Stream#map
是标准的习惯用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.