Search code examples
javalistdictionarytreemap

How to use Map, TreeMap with List in Java?


How can I transform the following data result

[a={x=0, y=43, z=57}, b={x=1, y=90, z=9}, c={x=1, y=83, z=16}]

into

{x=[0,1,1], y=[43,90,83], z=[57,9,16]}

using Map and Treemap.

Basically, I am iterating over a,b,c.. then while reading its values I want to sort them by Key(x),values(0,1,1), Key(y),values(43,90,83) and so on.

Thanks a lot for your help.


Solution

  • Obviously

    Map<String, Map<String, Integer>> mapOfMaps = ...
    TreeMap<String, List<Integer>> series = mapOfMaps.values().stream()
            .map(Map::entrySet)
            .flatMap(Set::stream)
            .collect(Collectors.groupingBy(Entry::getKey, TreeMap::new,
                    Collectors.mapping(Entry::getValue, Collectors.toList())));
    

    http://ideone.com/LHYhE7