简体   繁体   中英

Java 8 Converting List<Map<String,String> to Map<String,Map<String,String>>

I want to convert List of Map ie

List<Map<String,String> 

to Map Of Map ie

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

In List of Map I am storing Distanace between two Cities.My List of map is :

[{Destination=IOWA, distance=2000, Source=NY}, {Destination=OHIO, distance=3000, Source=NY}, {Destination=TX, distance=2500, Source=NY}, {Destination=NC, distance=1500, Source=TX}, {Destination=NY, distance=2500, Source=TX}, {Destination=DEL, distance=3000, Source=TX}]

Now I have to convert it into

MAP<String<Map<String,String>>, 

so that we can get distance from all city .Outer Map Key will be Source City. Value Map will have Destination City as Key and Distance between Source to Destination as value. Output will be in format:

{TX={NC=1500, DEL=3000, NY=2500}, NY={IOWA=2000, TX=2500, OHIO=3000}}

I want to convert it by using Java 8 Stream API. Not sure how to use groupingby.

As others have pointed out, you're not using the ideal structure for your data. But this should do what you want under the circumstances:

Map<String, Map<String, String>> distancesBySource = distances.stream()
        .collect(Collectors.groupingBy(m -> m.get("Source"),
                Collectors.toMap(m -> m.get("Destination"), m -> m.get("distance"))));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM