Skip to content
Advertisement

Stream API how to modify key and value in a map?

I have a String - Array map that looks like this

dishIdQuantityMap[43]=[Ljava.lang.String;@301d55ce
dishIdQuantityMap[42]=[Ljava.lang.String;@72cb31c2
dishIdQuantityMap[41]=[Ljava.lang.String;@1670799
dishIdQuantityMap[40]=[Ljava.lang.String;@a5b3d21

What I need to do is

  1. Create a new map, where key – only numbers extracted from String like this ( key -> key.replaceAll("\D+","");
  2. Value – first value from array like this value -> value[0];
  3. Filter an array so that only this paris left where value > 0

I’ve spent an hour trying to solve it myself, but fail with .collect(Collectors.toMap()); method.

UPD: The code I’ve done so far. I fail to filter the map.

HashMap<Long, Integer> myHashMap =  request.getParameterMap().entrySet().stream()
        .filter(e -> Integer.parseInt(e.getValue()[0]) > 0)
        .collect(Collectors.toMap(MapEntry::getKey, MapEntry::getValue));

Advertisement

Answer

You can do it by using stream and an auxiliary KeyValuePair class. The KeyValuePair would be as simple as:

public class KeyValuePair {

    public KeyValuePair(String key, int value) {
        this.key = key;
        this.value = value;
    }
    
    private String key;
    private int value;
    
    //getters and setters
}

Having this class you can use streams as bellow:

Map<String, Integer> resultMap = map.entrySet().stream()
            .map(entry -> new KeyValuePair(entry.getKey().replaceAll("Key", "k"), entry.getValue()[0]))
            .filter(kvp -> kvp.value > 0)
            .collect(Collectors.toMap(KeyValuePair::getKey, KeyValuePair::getValue));

In the example I’m not replacing and filtering exactly by the conditions you need but, as you said you are having problems with the collector, you probably just have to adapt the code you currently have.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement