kamil wilk
kamil wilk

Reputation: 117

Update object in list if exists if not add it to list

I would like to update object in list if exists, if add it to list.

I was able to write just updating, but I don't know how to add object to the list if was not present in the list using stream.

Code updating objects:

public List<Parameter> update(List<Parameter> oldParameters, List<Parameter> newParameters) {
        return oldParameters
                .stream()
                .map(p -> newParameters
                        .stream().
                        filter(u -> p.getName().equals(u.getName()))
                        .findFirst()
                        .orElse(p)).collect(Collectors.toList());
}

Parameter:

@Data
public class Parameter {

    private String name;
    private String value;
}

Test:

 def "Should update value if exists"() {
        given:

        List<Parameter> oldParameters = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            Parameter parameter = new Parameter("nameTest" + i, "oldValue" + i)
            oldParameters.add(parameter)
        }
        List<Parameter> currentParameters = new ArrayList<>();
        for (int i = 5; i < 10; i++) {
            Parameter parameter = new Parameter("nameTest" + i, "newValue" + i)
            currentParameters.add(parameter)
        }

        when:
        def result = subject.update(oldParameters,currentParameters)

        then:
        result.get(5).getValue() == "newValue5"
        result.get(6).getValue() == "newValue6"
        result.get(7).getValue() == "newValue7"
        result.get(8).getValue() == "newValue8"
        result.get(9).getValue() == "newValue9"
    }

    def "Should add objects to the list if not exists"() {
        given:

        List<Parameter> oldParameters = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            Parameter parameter = new Parameter("nameTest" + i, "oldValue" + i)
            oldParameters.add(parameter)
        }
        List<Parameter> currentParameters = new ArrayList<>();
        for (int i = 5; i < 10; i++) {
            Parameter parameter = new Parameter("newParameter" + i, "newValue" + i)
            currentParameters.add(parameter)
        }

        when:
        def result = subject.update(oldParameters,currentParameters)

        then:
        result.size() == 30
    }

Thanks for any advance! Best Regards

Upvotes: 0

Views: 1735

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

You are using the wrong collection type. You should be using a Map<String,Parameter> with the "key" being the parameter name and the "value" being the Parameter object. Then just use Map#put(key,value). If the key already exists the value will be replaced, otherwise the key and value will be added. If you need a consistently ordered List view just use a LinkedHashMap<>.

Upvotes: 1

Related Questions