Java8 Streams: Remove an field from an object of the map value

Viewed 346

I have a hash map like this

Map<String, AttributeValueUpdate> myMap = new HashMap<>;

The class AttributeValueUpdate looks like this:

public class AttributeValueUpdate {
    private AttributeValue value;
    private String action;   
    
    public static class Builder {
        private AttributeValue value;
        private String action;

        public Builder() {
        }

        public AttributeValueUpdate.Builder withValue(AttributeValue value) {
            this.value = value;
            return this;
        }

        public AttributeValueUpdate.Builder withAction(String action) {
            this.action = action;
            return this;
        }

        protected void populate(AttributeValueUpdate instance) {
            instance.setValue(this.value);
            instance.setAction(this.action);
        }

        public AttributeValueUpdate build() {
            AttributeValueUpdate instance = new AttributeValueUpdate();
            this.populate(instance);
            return instance;
        }
    }
}

The map has two entries

AttributeValueUpdate att1 = AttributeValueUpdate.builder().withAction("Add").withValue(new AttributeValue("sam").build();
AttributeValueUpdate att2 = AttributeValueUpdate.builder().withAction("Delete").withValue(new AttributeValue("john").build();
myMap.add("entry1", attr1);
myMap.add("entry2", atte2);

I want to modify mymap by deleting the "value field" from all the AttributeValueUpdate (which is value of the map), basically map's value field will be changed by removing "value field" of the AttributeValueUpdate object. How can I achieve this using java streams?

1 Answers

Java Stream API is not a friend with Map as long as it's collection-based (List, Set). You need to stream over the entries of the map.

As far as I understand, you want to remove (= make null) AttributeValue value of each AttributeValueUpdate instance (map's value). Here is the way to go assuming a constructor AttributeValueUpdate(String action):

Map<String, AttributeValueUpdate> updatedMap = myMap.entrySet().stream()
    .map(entry -> {
        String action = entry.getValue().getAction();
        AttributeValueUpdate update = new AttributeValueUpdate(action);
        return new SimpleEntry<>(entry.getKey(), update);
    })
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

The easiest solution is using Map#replaceAll if you don't mind to mutate the map:

myMap.replaceAll((k, v) -> {
    String action = v.getAction();
    return new AttributeValueUpdate(action);
});
Related