Java uses void method to match threads?

Let's say I have a void method that simply transforms an object without returning any value, and I want to use it in the context of the stream map () function, for example:

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 compiled for simplicity - the actual method does something else, rather than just removing the UUID of the object.

In any case, how can you use the void method in a scenario like the above? Of course, I could force the method to return the transformed object, but which, apart from the point, violates the design (the method must be invalid).

+5
source share
3 answers

, java 8. forEach.

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

, , , peek

+6

In addition to Eugene’s answer, you can use Stream::mapas follows:

objList.stream()
   .map(e -> {
      transform(e, e.getUuid()); 
      return e;
   }).collect(Collectors.toList());

In fact, you do not want to convert your current elements and assemble them into a new one List.

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

Therefore, you must use Collection::forEachand return List.

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

Source: https://habr.com/ru/post/1667136/


All Articles