Reputation: 139
I have a Map<Integer, Map<String, List< String >>. I want to flatten it to Map<String, String> where the key is the inner map's key and the value is the inner map's lists first element using java 8.
Here is what I have so far
public static void main(String[] args) {
Map<Integer, Map<String, List<String>>> ip = new HashMap<>();
Map<String, List<String>> iip1 = new HashMap<>();
List<String> ilp1 = new ArrayList<>();
ilp1.add("Uno");
ilp1.add("Dos");
ilp1.add("Tres");
iip1.put("Alpha", ilp1);
Map<String, List<String>> iip2 = new HashMap<>();
List<String> ilp2 = new ArrayList<>();
ilp2.add("One");
ilp2.add("Two");
ilp2.add("Three");
iip2.put("Beta", ilp2);
Map<String, List<String>> iip3 = new HashMap<>();
List<String> ilp3 = new ArrayList<>();
ilp3.add("Eins");
ilp3.add("Zwei");
ilp3.add("Drei");
iip3.put("Gamma", ilp3);
ip.put(1, iip1);
ip.put(2, iip2);
ip.put(3, iip3);
Map<String, String> op =
ip.values().stream().collect(Collectors.toMap(Map.Entry::getKey, e ->
e.values().stream().map(ele -> ele.get(0))));
System.out.println(op);
}
However, I get an error for Map.Entry::getKey
saying Non-static method cannot be referenced from a static context
.
Not sure what is the issue here, Any help is much appreciated.
Upvotes: 1
Views: 555
Reputation: 60045
You have to use flatMap
first to get all the entrySet
, and then you can use Collectors.toMap
, like this:
Map<String, String> op = ip.values().stream()
.flatMap(e -> e.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get(0)));
Upvotes: 5