Search code examples
javalambdaone-liner

Is it possible to compress this expression to one line?


i have this java function that searches for an object in an arraylist based on the name variable of the object

public Animal buscarAnimal(String animal){ 
        for(Animal a: animais){
            if(a.getNomeAnimal().equals(animal))return a;
        }
        return null;

I was wondering if it is possible to do all of the compararisons and the returning of the object all in one line, using foreach and lambdas, or maybe streams. I tried for a some time, but i'm not really a pro and only got this far

animais.forEach((Animal a)->{if(a.getNomeAnimal().equals(animal)){return a;}});

This however gives me the following error:

error: incompatible types: bad return type in lambda expression

Solution

  • Use a Stream and filter then findFist. This returns an Optional<Animal>. If you don't want to change your method to return an Optional<Animal> (recommended), use orElse(null) to get your original behaviour.

    return
        animais.stream().filter(a -> a.getNomeAnimal().equals(animal))
        .findFirst()
        .orElse(null);
    

    In one line:

    return animais.stream().filter(a -> a.getNomeAnimal().equals(animal)).findFirst().orElse(null);