Java使用void方法进行流映射?

时间:2021-11-08 19:09:48

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方法?当然,我可以让方法返回转换后的对象,但这是除了点之外并且违反了设计(方法应该是无效的)。

3 个解决方案

#1


10  

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;

#2


6  

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

如果您确定这是您想要做的,那么请使用peek而不是map

#3


4  

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

除了Eugene的答案,你可以像这样使用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. Instead you want to apply a method for each entry in your 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;

#1


10  

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;

#2


6  

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

如果您确定这是您想要做的,那么请使用peek而不是map

#3


4  

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

除了Eugene的答案,你可以像这样使用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. Instead you want to apply a method for each entry in your 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;