Java 8 nested streams : return a value in last stream

Dapangma :

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.

Avneet Paul :
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()

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475886&siteId=1