You want something like this:
List<Map<String, String>> result = four.stream() // iterate the Map with values
.map(map -> map.entrySet() // .. for each one
.stream() // .. stream and collect
.collect(Collectors.toMap( // .. into a new Map
e -> one.get(e.getKey()), // .. with a key from the `one` Map
Map.Entry::getValue))) // .. and the same value
.collect(Collectors.toList()); // and pack as a List
The output on calling result.forEach(System.out::println);
is (remember that HashMap
is unordered):
{Engineer=Software Engineer, Doctor=MBBS}
{Engineer=Aerospace Engineer, Doctor=Ortho}
If you want the keys in each map sorted, you need to use the TreeMap
implementation and an overloaded Collectors.toMap(Function, Function, BinaryOperator, Supplier)
. However, the default behavior of the merger BinaryOperator
in the previous Collectors.toMap(Function, Function)
method is that it throws an exception on duplicated keys. You have to implement this one by yourself.
BinaryOperator<String> throwingMerger = (u,v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
};
List<Map<String, String>> result = four.stream() // iterate the Map with values
.map(map -> map.entrySet() // .. for each one
.stream() // .. stream and collect
.collect(Collectors.toMap( // .. into a new Map
e -> one.get(e.getKey()), // .. with a key from the `one` Map
Map.Entry::getValue, // .. and the same value
throwingMerger, // .. failing fast on duplicated keys
TreeMap::new))) // .. as TreeMap
.collect(Collectors.toList()); // and pack as a List
{Doctor=MBBS, Engineer=Software Engineer}
{Doctor=Ortho, Engineer=Aerospace Engineer}
5
solved Create a map with values of one map as key and values of each map as values from a list of maps [closed]