Stellar Sword
Stellar Sword

Reputation: 6226

Using Java Streams to pull out a key from a list of maps, and create a map of a map

I'm trying to move an item from inside a Map to outside the Map.

I'm trying to get the rowIdentifier out of the List below:

List<Map<Object,Object>>

// [{"rowIdentifier": "s5", "rowKey1": 5, "rowKey2": 7},{"rowIdentifier": "s7", "rowKey1": 9, "rowKey2": 9}]

into result Map<Map<Object,Object>>

// {"s5": {"rowKey1": 5, "rowKey2": 7}, "s7": {"rowKey1": 9, "rowKey2": 9}

I'm having a bit of trouble understanding groupingBy and collect(Collectors.mapping) vs. Collectors.toMap (I'm not sure I understand the difference between 'mapping' vs. 'toMap' functions in Java Streams. Or if I even need that.

DictByRowIdentifier[r["rowIdentifier"]] is the way I'm planning on calling it later.

A lot of examples on the web seem to simply collect it to a List or a Set. They don't seem to throw it back into another Map so examples are hard to find.

Upvotes: 4

Views: 88

Answers (1)

Bohemian
Bohemian

Reputation: 424973

To answer your direct question, you want toMap(), twice:

List<Map<String, String>> listOfMaps = new ArrayList<>(); // populated elsewhere
Map<String, Map<String, String>> mapOfMaps = listOfMaps.stream()
        .collect(Collectors.toMap(m -> m.get("rowIdentifier"), 
            m -> m.entrySet().stream().filter(e -> !e.getKey().equals("rowIdentifier"))
              .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))));

I changed the types to String, because that's what they are and it makes everything compile without warnings.

Upvotes: 4

Related Questions