简体   繁体   中英

Java streams: throwing exception from stream depending upon value in stream

Consider below dummy code:

List<Integer> intList = new ArrayList<>();
intList.add(10);
intList.add(20);
intList.add(30);

intList.stream().filter(i -> i > 40)
    .throwIf(size of list <= 0)
    .collect(Collectors.toList());

is there any feature available in java streams which will achieve something like above code?

Note: Above code is just the representation of what I am doing, its not the exact code I am looking for.

You could check if there's any element that passed your filter, and use Optional 's orElseThrow to throw an exception if there isn't :

Integer match = 
    intList.stream()
           .filter(i -> i > 40)
           .findAny()
           .orElseThrow(...);

Of course, this will only give you one of the elements that pass the filter when the exception isn't thrown, so I'm not sure if it's exactly what you want.

If you want to return the list if its size exceeds n elements, you might use the collectingAndThen collector:

List<Integer> list = 
    intList.stream()
           .filter(i -> i > 40)
           .collect(collectingAndThen(toList(), l -> { if (l.isEmpty()) throw new WhatEverRuntimeException(); return l;}));

However it might not be as readable as it gets, so you could simply add an if statement after collecting the results:

List<Integer> list = intList.stream().filter(i -> i > 40).collect(toList());
if (list.isEmpty()) {
    throw new WhatEverRuntimeException();
}

Finally, if the lower size limit is, let's say, 100, you might not want to build the list. In this case, you may use two stream pipelines, one to count the number of elements satisfying the lower bound you set, and one to actually build the list:

long count = intList.stream().filter(i -> i > 40).count();
if(count < limit) {
    throw new WhatEverRuntimeException();
}
List<Integer> list = intList.stream().filter(i -> i > 40).collect(toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM