I have a class UserCourseEntity with a property userId
@AllArgsConstructor
@Getter
@ToString
public static class UserCourseEntity {
private String userId;
}
And I have a map with UserCourseEntity objects as values.
public final Map<String, UserCourseEntity> userCourses;
Method getUserCoursesByUserID receives userId property of the UserCourseEntity as a parameter.
I want to check if there are values in the userCourses map having userId that matches the giving id in the case-insensitive manner (i.e. using equalsIgnoreCase()).
If there are such values, I need to store them into a list, and throw an exception otherwise.
I'm wonder is it possible to reimplement this code using streams?
public List<UserCourseEntity> getUserCoursesByUserID(String userId) {
List<UserCourseEntity> list = new ArrayList<>();
for (Map.Entry<String, UserCourseEntity> entry : userCourses.entrySet()) {
UserCourseEntity userCourseEntityValue = entry.getValue();
String key = entry.getKey();
boolean isExist = userCourseEntityValue.getUserId().equalsIgnoreCase(userId);
if (!isExist) {
continue;
} else {
if (userCourseEntityValue.getUserId().equalsIgnoreCase(userId)) {
list.add(userCourses.get(key));
}
}
}
if (list.isEmpty()) {
logger.error("No data found");
throw new SpecificException("No data found with the given details");
}
return list;
}