stream().filter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

stream().filter

animalList().stream().filter(animal -> animal.getId() == id).findFirst().orElse(null); nimalList().stream().filter(animal -> animal.getId() == number).findFirst().isPresent(); Can you explan me how the code work and what the benefit each method in code ?

1st Sep 2021, 9:12 PM
Nora
Nora - avatar
1 Answer
0
.stream() take animal .filter() send to next if it is "Bonobo" else take other animal .findFirst() stop if find .orElse() if not find anything return null .isPresent() return true if find import java.util.*; public class Program { public static void main(String[] args) { List<String> animals = List.of( "Orangutan","Gorilla","Bonobo", "Chimpanzee","Human"); String res1 = animals.stream() .filter( animal -> animal == "Bonobo") .findFirst().orElse(null); boolean res2 = animals.stream() .filter( animal -> animal == "Human") .findFirst().isPresent(); System.out.println( res1); System.out.println( res2); } }
3rd Sep 2021, 12:59 AM
zemiak