Issue
I have some existing code where I need to add a conditional. In the below, if the value of "at" is "FOOBAR", then instead of "accessTypeHit.right.getSortValues()" I need "accessTypeHit.right.getSourceAsString()". Otherwise, it should still be "accessTypeHit.right.getSortValues()".
Due to the complexity of the nested lambda, I am having difficulty figuring out how to address this. I would be grateful for any ideas. thanks.
public class DSHTAFunction implements Function<SearchHits, List<ImmutablePair<String, Set<AObject>>>> {
@Override
public List<ImmutablePair<String, Set<AObject>>> apply(@NonNull SearchHits searchHits) {
return StreamSupport.stream(searchHits.spliterator(), false).map(searchHit -> {
String id = searchHit.getFields().get(ID_FIELD).getValue();
Set<AObject> AObjects = Sets.newHashSet();
AObjects.addAll(ATM.INSTANCE.getTypes().stream()
.flatMap(at -> {
if (searchHit.getInnerHits() == null) {
return Stream.empty();
}
return Arrays.stream(searchHit.getInnerHits().getOrDefault(at.getIFName(), SearchHits.empty())
.getHits()).map(h -> ImmutablePair.of(at, h));})
.flatMap(accessTypeHit ->
Arrays.stream(accessTypeHit.right.getSortValues())
.filter(sv -> sv != null)
.map(sv -> new AObject(accessTypeHit.left, sv.toString())))
.filter(AObject::isNonDefault).collect(Collectors.toSet()));
return ImmutablePair.of(id, AObjects);
}).collect(Collectors.toList());
}
Solution
Extract every nested flatMap function into its own method. Then your work will become much simpler
public class DSHTAFunction implements Function<SearchHits, List<ImmutablePair<String, Set<AObject>>>> {
@Override
public List<ImmutablePair<String, Set<AObject>>> apply(@NonNull SearchHits searchHits) {
return StreamSupport.stream(searchHits.spliterator(), false).map(this::hitsToPairs).collect(Collectors.toList());
}
private ImmutablePair<String, Set<AObject>> hitsToPairs(SearchHit searchHit) {
String id = searchHit.getFields().get(ID_FIELD).getValue();
Set<AObject> AObjects = ATM.INSTANCE.getTypes().stream()
.flatMap(at -> accessTypeHits(searchHit, at))
.flatMap(this::toAObject)
.collect(Collectors.toSet());
return ImmutablePair.of(id, AObjects);
}
private Stream<ImmutablePair<AccessType, Hit>> accessTypeHits(SearchHit searchHit, AccessType at) {
if (searchHit.getInnerHits() == null) {
return Stream.empty();
}
return Arrays.stream(searchHit.getInnerHits().getOrDefault(at.getIFName(), SearchHits.empty()).getHits())
.map(h -> ImmutablePair.of(at, h));
}
private Stream<AObject> toAObject(ImmutablePair<AccessType, Hit> accessTypeHit) {
return Arrays.stream(accessTypeHit.right.getSortValues())
.filter(Objects::nonNull)
.map(sv -> new AObject(accessTypeHit.left, sv.toString())))
.filter(AObject::isNonDefault);
}
}
Answered By - SimY4