Reputation: 107
I'm trying to refactor the following code to a lambda function:
private Optional<String> fetchByNumList(ObjectId objectId) {
List<Reference> numList = objectId.getNumList();
if (!numList.isEmpty()) {
for (Reference numRef : numList) {
Optional<String> otherNum = findOtherNum(numRef);
if (otherNum.isPresent()) {
return otherNum;
}
}
}
return Optional.empty();
}
private Optional<String> findOtherNum(Reference numRef) {
List<String> numRefList = numRef.getNumRefList();
if (!numRefList.isEmpty()) {
for (String num : numRefList) {
Matcher matcher = REGEX_PATTERN.matcher(num);
if (matcher.matches()) {
return Optional.of(matcher.group(3));
}
}
}
return Optional.empty();
}
This is what i have so far:
private Optional<String> fetchByNumListLambda(ObjectId objectId) {
return objectId.getNumList().stream()
.map(numRef -> { numRef.getNumRefList().stream()
.map(num -> {
Matcher matcher = REGEX_PATTERN.matcher(num);
if (!matcher.matches()) {
return Optional.of(matcher.group(3));
}
return Optional.<String>empty();
});
return Optional.<String>empty(); //I believe this is the one, overriding the value to Optional.empty.
})
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
}
However, when I run, it returns Optional.empty. I'm sure it could be clean up, I'm still trying to get the hang of lambdas. Thanks!
Upvotes: 1
Views: 426
Reputation: 9586
private Optional<String> fetchByNumList(ObjectId objectId) {
return objectId.getNumList().stream()
.map(n -> n.getNumRefList().stream()
.map(REGEX_PATTERN::matcher)
// pre Java 11 .filter(m -> !m.matches())
.filter(Predicate.not(Matcher::matches))
.findAny()
.map(p -> Optional.of(p.group(3)))
.orElse(Optional.empty()))
.findAny()
.orElse(Optional.empty());
}
Upvotes: 1
Reputation: 304
I believe your lambda function is not equal to your nested loop. In your nested loop you check whether "matcher.matches()", if outcome is true you return Optional.of(matcher.group(3)).
However the statement in your lambda function does the opposite, you check for "!matcher.matches()", and then return Optional.of(matcher.group(3)).
I think it returns Optional.empty because your code in the lambda should be:
if (matcher.matches()) {
return Optional.of(matcher.group(3));
}
Instead of:
if (!matcher.matches()) {
return Optional.of(matcher.group(3));
}
Upvotes: 0