Reputation: 4637
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.
Upvotes: 5
Views: 2774
Reputation: 93892
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());
Upvotes: 2
Reputation: 394136
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.
Upvotes: 6