Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 nested streams : return a value in last stream

This question can be considered as based on java 8 nested streams

Suppose I have a Batch with Baskets with Items :

public class Batch {
    private List<Basket> baskets;
}

public class Basket {
    private List<Item> items; 
}

public class Item {
    private String property;
    private int value;
}

I would like to rewrite this method with Java 8 streams.

public class SomeService {
    public int findValueInBatch(Batch batch) {
        for (Basket basket : batch.getBaskets()) {
            for (Item item : basket.getItems()) {
                if (item.getProperty().equals("someValue") {
                    return item.getValue();
                }
            }
        }
        return 0;
    }
}

How should I do it ?

First step to where I'd like to go :

public int findValueInBatch(Batch batch) {
    for (Basket basket : batch.getBaskets()) {
        basket.getItems().stream()
            .filter(item -> item.getProperty.equals("someValue") 
            .findFirst()
            .get();
            // there I should 'break'
    }
}

Thanks a lot.

like image 619
Dapangma Avatar asked Apr 19 '17 14:04

Dapangma


1 Answers

baskets.stream()
            .flatMap(basket -> basket.getItems().stream())
            .filter(item -> item.equals("someValue"))
            .findAny()
            .orElseThrow(NoSuchElementException::new);

The advantage of using findAny instead of findFirst is that findFirst doesn't work with parallel streams. Therefore, if you want to parallelize the above operation all you'll need to do is replace the stream() method with parallel()

like image 130
Avneet Paul Avatar answered Sep 24 '22 02:09

Avneet Paul