Post

TroubleShooting_Get just one user role as string from list

๐Ÿ”ด From user role list, I want to get just one role as String

์œ ์ €๋กค ๋ฆฌ์ŠคํŠธ์—์„œ ์—ญํ•  ํ•˜๋‚˜๋งŒ ์ŠคํŠธ๋ง์œผ๋กœ ๋ฐ›๊ณ  ์‹ถ๋‹ค

๐ŸŸก Identify error

Each user has a user role list.
The user will have just one role, but the role is saved as a list.
But I would like to check just the role of the user.
This is for checking the userโ€™s role and if the user has role ADMIN, give the permission to run certain functions.

And if the user does not have the role ADMIN, not let the user do such functions.

Thus, get the role name from the role list, and I should fetch the very first role.

๐Ÿ”ต Tryout 1. stream.map.findFirst()

1
String role= user.getUserRole().stream().map(ur-> ur.getRole().getRoleName()).findFirst();

๐Ÿ”ด Fail.
Getting role name from user role list will result in role name list.
The result has to be String

๐Ÿ”ต Tryout 2. Get user role name and save to role name list

1
2
3
4
// Get user role name and save to role name list
List<String> role= user.getUserRole().stream().map(ur-> ur.getRole().getRoleName()).collect(Collectors.toList());
// And then find the first among the list
role.stream().findFirst()

๐ŸŸก Success, But there seems to be cleaner code.

๐Ÿ”ต Tryout 3. Optional[ROLE_ADMIN]

1
Optional<String> role=

๐Ÿ”ด Fail.
Need to get result as String to compare, however the result of this code will return optional.
The result has to be String

๐ŸŸข Solution

1
role.stream().findFirst().get().equals("ROLE_ADMIN")

๐ŸŸขย Success.
First, to get rid of Optional do findFirst(), then to compare the value use get()

First, unwrap the Optional returned by findFirst() and then compare its value to โ€œROLE_ADMINโ€.
You can do this using the isPresent() and get() methods of the Optional class.

This post is licensed under CC BY 4.0 by the author.