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 information given:
Arrays.asList("Débora", "Luan").stream().filter(parametroFiltro -> parametroFiltro.equals("Luan")).findFirst().get();
I used some tools available from version 1.8 of Java. With lambda expressions it is easier to write small functional classes with only one method, which takes a parameter (the Filter parameter), and defines it within a method (so the arrow, ->, is used to indicate how it will be executed).
For example, the method filter
used after the stream
is used to "filter" the collection from a given check.
The code .filter(parametroFiltro -> parametroFiltro.equals("valor")
may be replaced by:
.filter(new Predicate<String>(){
@Override
public boolean test(String parametroFiltro) {
return parametroFiltro.equals("Luan");
}
})
In the case of filter, as it expects an instantiated object from the Predicate interface, it knows that it must execute the defined code is parametroFiltro -> parametroFiltro.equals("valor")
as a method that has something like return and takes only a String type parameter.
The second use of lambda was used to define as a parameter reducing
an instance of the Binaryoperator class, which has the method apply
as a method that takes two variables and returns a type T, defined in the anonymity class creation. in this case:
Collectors.reducing(new BinaryOperator<String>() {
@Override
public String apply(String a, String b) {
return null;
}
}
There’s no charge on that, I told you because I thought it was cool to share more fun ways of dealing with it.
And anyway, please, if more studied people on the subject manage to complete the information I am immensely grateful.
Be more specific about what you are trying to do. Give an example of the objects you have and the type of search you want to do.
– Isac