Variable is already defined in method lambda

Let's go to the Java Language Specification on names and their scopes

The scope of a formal parameter of a method (§8.4.1), constructor (§8.8.1), or lambda expression (§15.27) is the entire body of the method, constructor, or lambda expression.

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

Then, on the subject of shadowing and obscuring

A local variable (§14.4), formal parameter (§8.4.1, §15.27.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name, not a qualified name (§6.2).

Some declarations are not permitted within the scope of a local variable, formal parameter, exception parameter, or local class declaration because it would be impossible to distinguish between the declared entities using only simple names.

It is a compile-time error if the name of a local variable v is used to declare a new variable within the scope of v, unless the new variable is declared within a class whose declaration is within the scope of v.

So, in

User user = users.stream().filter((user) -> user.getId() == 1).findAny().get();

, the scope of the variable user is everything after it in that block. Now you are trying to use the name of that variable to declare a new variable within the scope, but not

within a class whose declaration is within the scope of v.

so a compile time error occurs. (It's declared in a lambda expression, not in a class.)


look at the code

User user = users.stream().filter((user) -> user.getId() == 1).findAny().get();

The variable name is user and the variable inside the lambda is also user

try changing it to be something like this

User user = users.stream().filter((otherUser) -> otherUser.getId() == 1).findAny().get();

It is the same as with any other local variables: you're not allowed to shadow them in more inner {} blocks.