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 ?
1 ответ
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);
}
}