Java use void method for stream mapping?

て烟熏妆下的殇ゞ 提交于 2020-08-18 10:06:05

问题


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:

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.

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).


回答1:


Seems like this is a case of forced usage of java 8 stream. Instead you can achieve it with forEach.

List<MyObject> objList = ...
objList.forEach(e -> transform(e, e.getUuid()));
return objList;



回答2:


If you are sure that this is what you want to do, then use peek instead of map




回答3:


In addition to Eugene's answer you could use Stream::map like this:

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.

Instead, you want to apply a method for each entry in your List.

Therefore you should use Collection::forEach and return the List.

List<MyObject> objList = ...;
objList.forEach(e -> transform(e, e.getUuid()));
return objList;


来源:https://stackoverflow.com/questions/41719914/java-use-void-method-for-stream-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!