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.