I am performing some actions on a stream and returning an array list. This is working without a problem but I need to do a final step to add an element if the array list is empty (nothing to do with options / nulls just part of the requirement) My way is a bit clunky and I wondered if it can be done in the stream operation instead?
public ArrayList<String> getArrayList () {
ArrayList<String> aL = setOfStrings.stream()
.filter(remove some)
.filter(remove some more)
.map(i -> createStringAbout(i))
.collect(Collectors.toCollection(ArrayList::new));
if (aL.size() < 1) {
aL.add("No items passed the test");
}
return aL;
}
So really I would like to do
return set.stream()...
is this possible ?
To insert an element at the end of a stream, we need to change the order in which the arguments were passed to the Stream. concat() method. Now the resultant stream from the given element is passed as the second parameter to the Stream. concat() method.
Java Stream collect() is mostly used to collect the stream elements to a collection. It's a terminal operation. It takes care of synchronization when used with a parallel stream. The Collectors class provides a lot of Collector implementation to help us out.
That means list. stream(). filter(i -> i >= 3); does not change original list. All stream operations are non-interfering (none of them modify the data source), as long as the parameters that you give to them are non-interfering too.
Use collectingAndThen
.collect(Collectors.collectingAndThen(ArrayList::new, rs -> {
if(rs.size() < 1 ) {
rs.add("something");
}
return rs;
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With