Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a default item to a stream collection

Tags:

java

java-8

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 ?

like image 382
gringogordo Avatar asked Jan 29 '18 10:01

gringogordo


People also ask

How do you add an object to a stream?

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.

What does collect () do in Java?

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.

Do streams modify original list?

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.


1 Answers

Use collectingAndThen

.collect(Collectors.collectingAndThen(ArrayList::new, rs -> {
                    if(rs.size() < 1 ) {
                        rs.add("something");
                    }
                   return rs;
                })
like image 160
pvpkiran Avatar answered Oct 14 '22 07:10

pvpkiran