java Java使用void方法进行流映射?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41719914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java use void method for stream mapping?
提问by Nestor Milyaev
Let's say I have a void method that just does transformation on an object, without returning any value, and I want to use it in a context of a stream map() function, like this:
假设我有一个 void 方法,它只对对象进行转换,不返回任何值,并且我想在流 map() 函数的上下文中使用它,如下所示:
public List<MyObject> getList(){
List<MyObject> objList = ...
return objList.stream().map(e -> transform(e, e.getUuid())).collect(Collectors.toList());
}
private void transform(MyObject obj, String value){
obj.setUuid("prefix" + value);
}
The example is made up for simplicity - the actual method is doing something else than just mucking up the UUID of an object.
该示例是为了简单起见 - 实际方法正在做其他事情,而不仅仅是弄乱对象的 UUID。
Anyway, how is that possible to use a void method in a scenario like the above? Surely, I could make the method return the transformed object, but that's besides the point and is violating the design (the method should be void).
无论如何,在上述场景中如何使用 void 方法?当然,我可以让该方法返回转换后的对象,但除此之外,这违反了设计(该方法应该是无效的)。
回答by Murat Karag?z
Seems like this is a case of forced usage of java 8 stream. Instead you can achieve it with forEach.
似乎这是强制使用 java 8 流的情况。相反,您可以使用 forEach 实现它。
List<MyObject> objList = ...
objList.forEach(e -> transform(e, e.getUuid()));
return objList;
回答by Eugene
If you are sure that this is what you want to do, then use peekinstead of map
如果您确定这是您想要做的,那么请使用peek而不是 map
回答by Flown
In addition to Eugene's answeryou could use Stream::map
like this:
除了尤金的回答,你可以这样使用Stream::map
:
objList.stream()
.map(e -> {
transform(e, e.getUuid());
return e;
}).collect(Collectors.toList());
Actually, you don't want to transform your current elements and collect it into a new List
.
实际上,您不想转换当前元素并将其收集到新的List
.
Instead, you want to apply a method for each entry in your List
.
相反,您希望为List
.
Therefore you should use Collection::forEach
and return the List
.
因此,您应该使用Collection::forEach
并返回List
.
List<MyObject> objList = ...;
objList.forEach(e -> transform(e, e.getUuid()));
return objList;