JMBA
JMBA

Reputation: 109

Construct a new map using List of Maps using Java 8 streams

I converted below json data (in example) to List<Map<String, String>> and from that i want to construct a new Map using Java 8 streams and the output should look like below. could someone help me with this?

Key         value
Service1: DEACTIVATED
Service2: ACTIVATED
Service3: DEACTIVATED

Ex:

[
{
 name=Service1, 
 desiredState=DEACTIVATED
}, 
{
 name=Service2, 
 desiredState=ACTIVATED
}, 
{
  name=Service3, 
  desiredState=DEACTIVATED
}
]

Upvotes: 1

Views: 1517

Answers (2)

fps
fps

Reputation: 34470

If I get it well, you need to merge your maps in a way such that the value of the name key is the key that maps to the value of the desiredState key. You could do it this way:

Map<String, String> result = listOfMaps.stream()
    .collect(Collectors.toMap(
             m -> m.get("name"),
             m -> m.get("desiredState"),
             (o, n) -> n));

This assumes that all maps from the list have name and desiredState entries. The (o, n) -> n merge function must be provided, in case there are collisions when creating the result map (i.e. entries with the same key). Here, between old and new values, I've chosen the new value.

Upvotes: 0

Mohamed Anees A
Mohamed Anees A

Reputation: 4601

From what I could comprehend, you aim to convert List<Map<String,String>> to Map<String,String>.

 List<Map<String,String>> myMap = .... // map which you have already.
    
    Map<String,String> resultMap = myMap.stream()
                                   .flatMap(map ->  map.entrySet().stream())  // Get a flatMap of the entryset. This will form a stream of Map.Entry
                                   .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(), (k1, k2) -> k2));

Here (k1,k2) -> k2 is a merge function in case if there are multiple entries for same keys while constructing the resultMap.

Upvotes: 2

Related Questions