Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert map keys to uppercase in using java 8 streams?

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?

like image 832
Ajeetkumar Avatar asked Oct 10 '16 06:10

Ajeetkumar


People also ask

Can we convert map to stream in Java?

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.

Can we use map stream in Java 8?

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.


1 Answers

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()));
like image 192
svarog Avatar answered Sep 29 '22 04:09

svarog