Alexei
Alexei

Reputation: 15726

Replace loop and usages with Java streams

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.

Upvotes: 0

Views: 111

Answers (1)

Karthik R
Karthik R

Reputation: 5786

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

Upvotes: 2

Related Questions