Java 8
for (SomePojo nsVr : nsVrsList) {
Optional<MyCustomObject> findMyCustomObject = possibleValues.getValues().stream()
.filter(possibleValueItem -> possibleValueItem.getName().equals(nsVr.getName()))
.findAny();
if (!findMyCustomObject.isPresent()) {
possibleValues.getValues()
.add(new MyCustomObject(nsVr.getInstance(), nsVr.getInstance(), ""));
}
}
As result then list possibleValues.getValues() contain unique(no duplicate) items that equal (by name) to items from list nsVrsList.
Nice. It's work fine.
But now I want to replace previous code by streams.
possibleValues.getValues().addAll(possibleValues
.getValues().stream().filter(
currentPossibleValues -> nsVrsList.stream()
.anyMatch(currentSomePojo -> currentPossibleValues.getName()
.equals(currentSomePojo.getName())))
.collect(Collectors.toList()));
But as result the possibleValues.getValues() is empty.
new MyCustomObject(…)when there is no match whereas the second tries to find all matching elements ofpossibleValues.getValues(), followed by adding them topossibleValues .getValues()again. It should be obvious that they can’t be equivalent whennew MyCustomObjectdoesn’t appear in the second code snippet…possibleValues? also give minimal definition ofMyCustomObjectandSomePojo