I'm getting The final local variable token cannot be assigned, since it is defined in an enclosing type
compilation error at the token
inside the forEach
and lambda
. All I want to do is assign the only item in the list to token
variable.
PS: I know for sure that there is only one item in the list
.
public static void main(String[] args) throws Exception {
final StringBuilder token;
AuthResponse authResponse = new AuthResponse();
authResponse.getTokens().forEach(item -> {
token.append(item.getToken());
});
}
If I declare token
as an Instance variable
there is no problem. But is there any other way to do it?
There are a few posts regarding this but I'd like to understand the resolution for this issue
EDIT : I have updated the question to have StringBuilder
instead of String
You need to assign an instance:
StringBuilder token = new StringBuilder();
But why are you reinventing the wheel; use something like:
String tokens = new AuthResponse().getTokens().stream()
.map(Object::toString)
.collect(Collectors.joining(","));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.