I have the following userList of type List<Map<String, Object>> json array
[
{
"type": "OWNER",
"address": "xxxxxxx"
},
{
"type": "LOCATION",
"address": "sssssss"
}
:
]
I want to find if the any of the map object in list contains of type value "OWNER" or "ADMIN". I tried he below code
List<String> ownerList = new ArrayList<>();
ownerList.add("OWNER");
ownerList.add("ADMIN");
AtomicBoolean isUserOwner = new AtomicBoolean(false);
userList.forEach(user -> isUserOwner.set(user.entrySet()
.stream()
.filter(m -> m.getKey().contains("type"))
.anyMatch(map -> ownerList.contains(valueOf(map.getValue())))));
isUserOwner.get();// ---> get the boolean value which shows if it is either OWNER or ADMIN
The above code works fine, but can anyone please tell me if there is any other way in stream to check this efficiently
CodePudding user response:
You can do something like this instead.
userList.forEach(user -> isUserOwner.set(user.entrySet()
.stream()
.filter(m -> m.getKey().contains("type") && ownerList.contains(m.get("type")))
.findAny()
.isPresent()
);
The m.get() is safe because the RHS of the && is only evaluated if the LHS was true.
CodePudding user response:
If you just need to find if one of the elements is an owner or admin, you can use this:
boolean containsOwnerOrAdmin = users.stream()
.map(a -> a.get("type"))
.filter(Objects::nonNull)
.anyMatch(type -> ("OWNER".equals(type) || "ADMIN".equals(type)));
This loop through each map from the list getting an item with the key "type" and will filter out any null values, then it will check if any of the resulting Objects is equal to OWNER or ADMIN.
