The easiest way is:
Arrays.asList("Débora", "Luan").stream().filter(string -> string.equals("Luan"))
.collect(Collectors.reducing((a, b) -> null)).get();
Or even, what would be more protected in case there is no item that resembles the given information:
Arrays.asList("Débora", "Luan").stream().filter(parametroFiltro -> parametroFiltro.equals("Luan")).findFirst().get();
I've used some tools available since version 1.8 of Java. With lambda expressions it is easier to write small functional anonymous classes with only one method, which takes a parameter (the Filter parameter), and defines it inside a method (so the arrow, -> is used to indicate how it will be its execution).
For example, the filter
method used after stream
is used to "filter" the collection from a given check.
The code .filter(parametroFiltro -> parametroFiltro.equals("valor")
can be replaced by:
.filter(new Predicate<String>(){
@Override
public boolean test(String parametroFiltro) {
return parametroFiltro.equals("Luan");
}
})
In case of the filter, as it expects an object instantiated from the Predicate interface, it knows that it should execute the defined code is parametroFiltro -> parametroFiltro.equals("valor")
as a method that has something like return and only receives a parameter type String.
The second use of lambda was used to define as the parameter of reducing
an instance of the BinaryOperator class, which has method apply
as a method that receives two variables and returns a type T, defined in the creation of the anonymous class . in this case:
Collectors.reducing(new BinaryOperator<String>() {
@Override
public String apply(String a, String b) {
return null;
}
}
I do not know why I think it's cool to share more fun ways to handle it.
And in any case, please, if people who are more studied in the subject manage to complete the information, I am immensely grateful.