Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return void in stream?

I am haveing List of sending orders.It is increased when method name of parameter is same

But It is not working. Because It hasn't Termination operation

List<SendingOrdres> sendingOrders = new ArrayList<SendingOrdres>();

private void countUpOrResetSendingOrders(String method) {
    sendingOrders.stream()
                 .filter((e) -> {
                     System.out.println("filter:"+e);
                     return e.getMethod().equals(method);
                 })
                 .peek((e) -> System.out.println("peek:"+e)) //For check
                 .map((e)->{
                     int nextNowSendingOrder = e.getNowSendingOrder()+1;
                     if(nextNowSendingOrder > e.getMaxSendingOrder()) {
                         e.setNowSendingOrder(0);
                     }else {
                         e.setNowSendingOrder(nextNowSendingOrder);
                     }
                     return e;
                 });
                 // no Termination operation
}

I added Termination operation in upper code. It is working well.

.collect(Collectors.toList()); 

I have a question.I don't need to return value. So i want to return void.
But If Termination operation hasn't, Stream is not working. How to return void in stream?

like image 383
Carmel Avatar asked Aug 30 '21 09:08

Carmel


1 Answers

Stream consists of two mandatory (sourcing, terminal) and one optional (intermediate) parts.

Stream:

  • is generated with sourcing operation (something that creates the Stream<T> instance);
  • is then optionally continued with one or more, chained intermediate operation(s);
  • is finally terminated with terminal operation.

void can only be considered to be the return type of the terminal operation (hence, of its lambda (or method reference) expression) in the stream, because every intermediate operation has to return stream, upon which, subsequent intermediate (or terminal) operation would operate.

For example:

List.of(1, 2, 3, 4)
    .stream() //sourcing the stream
    .forEach(System.out::println); //terminating the stream

is OK, because println just consumes the stream and doesn't have to return another stream.


List.of(1, 2, 3, 4)
    .stream() //sourcing the stream
    .filter(System.out::println); //ouch..

however, does not compile.


Additionally, beware, that Stream API is lazy, in Java. Intermediate operations are not effectively evaluated, until the terminal operation is executed.

like image 175
Giorgi Tsiklauri Avatar answered Oct 11 '22 10:10

Giorgi Tsiklauri