0

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.

2
  • 2
    Your indentation is very confusing. Besides that, your first code snippet creates new objects using new MyCustomObject(…) when there is no match whereas the second tries to find all matching elements of possibleValues.getValues(), followed by adding them to possibleValues .getValues() again. It should be obvious that they can’t be equivalent when new MyCustomObject doesn’t appear in the second code snippet… Commented Sep 21, 2021 at 8:02
  • 2
    quite hard o get the code to compile for testing what type is possibleValues? also give minimal definition of MyCustomObject and SomePojo Commented Sep 21, 2021 at 14:10

1 Answer 1

2

The goal is to have unique value in the possibleValues from the list as I understand.

To make it less computationally intensive, try this:

Set<String> existingUniqueValueNames = possibleValues.getValues().stream()
                .map(val -> val.getName()).collect(Collectors.toSet());

List<MyCustomObject> newValues = nsVrsList.stream()
            .filter(nsVr -> !existingUniqueValueNames.contains(nsVr.getName())).map(nsVr -> {
                return new MyCustomObject(nsVr.getInstance(), nsVr.getInstance(),
                        nsVr.getName());
            }).collect(Collectors.toList());
// Aggregate
possibleValues.getValues().addAll(newValues);

P.S: If possible, the possibleValues.getValues() can be a Set instead of a List which does all these above computation by default, provided that you have correct toString() on MyCustomObject

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.