user1692342
user1692342

Reputation: 5237

Using java streams to create new map from existing map

I have a map which is of the following strucutre:

Map<String, Map<String, String>> input;

It basically contains, a set of IDs and for each ID, a value associated to an attribute.

For ex:
ID:       Attribute    Value
A           X           100
A           Y           200
B           X           40
B           Y           40

I am interested only in the attribute X for each ID and I want to do some processing and store it a new map which will have the same defintion Map>

I am trying this in Java 8:

Map<String, Map<String, String>> getResults(Map<String, Map<String, String>> input) {
    input.entrySet().stream()
        .map(id -> {
            String valueX = id.getValue().get("X");
            String computeX = compute(valueX);
            // Now start adding these results to the new map.
        } )
}

I am not able to follow, how I can add it to a new map.

Upvotes: 3

Views: 8315

Answers (1)

Eran
Eran

Reputation: 394156

You can collect the entries of the input map into a new map this way:

Map<String, Map<String, String>> getResults(Map<String, Map<String, String>> input) 
{
    return input.entrySet()
                .stream()
                .collect(Collectors.toMap(Map.Entry::getKey,
                                          e -> {
                                              Map<String,String> map = new HashMap<>(); 
                                              map.put("X",e.getValue().get("X")); 
                                              return map;
                                          }));
}
  • The keys of the output map are the same as the keys of the input map.

  • The values of the output map are constructed by creating a new HashMap<String,String> and putting in it the value of the "X" key.

Upvotes: 6

Related Questions