The variable result
was declared outside the lambda (in this case, outside the forEach
), then it can only be used within it if it’s final
.
But a variable final
may only have an assigned value only once. Only inside your own loop there is the possibility of it being set more than once (if you have more than one user with the email indicated, for example, you will enter twice in the if
, setting the variable final
twice).
That is, if you use final
, One mistake, but if you don’t use it, another.
So the solution is to refactor your code and not depend on setting the variable within the forEach
. Like getDatabase()
returns a Map
, just walk you through it with a for
normal:
public UserEntity findByEmail(String email) {
for (Map.Entry<Long, UserEntity> entry : getDatabase().entrySet()) {
if (entry.getValue().getEmail().equals(email)) {
// encontrou o email, já retorna o usuário
return entry.getValue();
}
}
// não encontrou nada, retorna null (ou pode lançar uma exceção)
return null;
}
The method entrySet
returns a set of Map.Entry
, from which it is possible to access the key and the respective value of the Map
. Using getValue()
, I get the UserEntity
, and then just do the checks you need.
But since you are only checking the values and ignoring the keys, you can only use the method values()
, that already returns directly all the UserEntity
:
public UserEntity findByEmail(String email) {
for (UserEntity user : getDatabase().values()) {
if (user.getEmail().equals(email)) {
// encontrou o email, já retorna o usuário
return user;
}
}
// não encontrou nada, retorna null (ou pode lançar uma exceção)
return null;
}
You need to put the ending in isName, which is the variable inside the foreach, not the result.
– Giuliana Bezerra
A variable declared outside the lambda (in this case, outside the
forEach
) can only be used within it if it’sfinal
. But a variablefinal
can only have a set value only once, but within that loop is the possibility of it being set more than once. So the solution is to refactor your code and not depend on setting the variable within the loop - using afor
normal, or, ifgetDatabase()
for a stream, usefilter
andfindFirst
, for example.– hkotsubo
getDatabase() does not have stream method...
– FearX
So please click on [Edit] and inform what is
getDatabase()
. Try to see if he has another method to travel it, for example– hkotsubo
Edited. The database is a map.
– FearX
To walk a
Map
, use afor
normal, so it doesn’t have this problem offinal
: https://stackoverflow.com/q/46898– hkotsubo