I have a method as below
private Map<String,List<String>> createTableColumnListMap(List<Map<String,String>> nqColumnMapList){
Map<String, List<String>> targetTableColumnListMap =
nqColumnMapList.stream()
.flatMap(m -> m.entrySet().stream())
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
return targetTableColumnListMap;
}
I want to uppercase the map keys but couldn't find a way to do it. is there a java 8 way to achieve this?
Converting complete Map<Key, Value> into Stream: This can be done with the help of Map. entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.
Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.
This doesn't require any fancy manipulation of Collectors. Lets say you have this map
Map<String, Integer> imap = new HashMap<>();
imap.put("One", 1);
imap.put("Two", 2);
Just get a stream for the keySet()
and collect into a new map where the keys you insert are uppercased:
Map<String, Integer> newMap = imap.keySet().stream()
.collect(Collectors.toMap(key -> key.toUpperCase(), key -> imap.get(key)));
// ONE - 1
// TWO - 2
Edit:
@Holger's comment is correct, it would be better (and cleaner) to just use an entry set, so here is the updated solution
Map<String, Integer> newMap = imap.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey().toUpperCase(), entry -> entry.getValue()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With