Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if stream().filter is empty

I want to know how to execute code from a stream if the filter does not find values and finds it, an example code:

 @Transactional
public void change(ClassName dep){
    // code
    dep.getFoo()
            .stream()
            .filter(f -> f.getName().equals(doo.getName))
            
}

if the filter has a value then:

user.setFoo(f);

if there is no value in the filter then:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Foo foo = new Foo();
foo.setName("Exp");
user.setFoo(foo);

>Solution :

I would suggest creating a constructor for Foo accepting name.

You can then extract the name with default value of Optional:

Foo foo = dep.getFoo()
        .stream()
        .filter(f -> f.getName().equals(doo.getName))
        .findAny().orElse(new Foo("Exp"));
user.setFoo(foo);

Since java 11 you can use ifPresentOrElse in a cleaner way:

dep.getFoo()
        .stream()
        .filter(f -> f.getName().equals(doo.getName))
        .findAny()
        .ifPresentOrElse(user::setFoo, () -> user.setFoo(new Foo("Exp")));

P.S.: If you cannot create the constructor, you can just create the method to provide it and use it in the above snippet:

public static Foo defaultFoo() {
    Foo foo = new Foo();
    foo.setName("Exp");
    return foo;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading