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

20,137

Solution 1

Answer for your question [which you can copy and paste] :

Map<String, List<String>> targetTableColumnListMap = nqColumnMapList.stream().flatMap(m -> m.entrySet().stream())
                .collect(Collectors.groupingBy(e -> e.getKey().toUpperCase(), Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

Solution 2

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()));
Share:
20,137
Ajeetkumar
Author by

Ajeetkumar

Updated on July 09, 2022

Comments

  • Ajeetkumar
    Ajeetkumar almost 2 years

    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?

  • cody123
    cody123 over 7 years
    It will be better if when you down-vote you should better give some explanation. Just silently down-voting won't make you more intelligent , You are still not intelligent because you down-voted without watching what I wanted to convey.
  • Holger
    Holger over 7 years
    Redefining the task, changing both, input and output, to come to the conclusion that it can be implemented simpler than the OP’s actual task, is not a real solution. Besides that, streaming over the keySet might look simpler, but performing a lookup for every key is a waste of resources, compared to streaming over the entrySet() in the first place, which provides the mapped value for free.
  • Ajeetkumar
    Ajeetkumar over 7 years
    pls provide the reason to downvote because it worked for me.
  • Snekse
    Snekse over 6 years
    My gut says the answer provided by @svarog would be faster.