简体   繁体   中英

Convert Map<Integer, String> to Map<String, String>

I want to convert Map to Map

So far i tried below

Map<Integer, String> inMap = new HashMap();
        inMap.put(100, "Test1");
        inMap.put(101, "Test2");
        inMap.put(102, "Test3");

How do i apply String.valueOf() on Entry::getKey?

    Map<String, String> collect = inMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue));  //how to apply String.valueOf() on Entry::getKey

This is working

    Map<String, String> map1 = inMap.entrySet().stream().collect(Collectors.toMap(entry -> String.valueOf(entry.getKey()), Map.Entry::getValue, (a, b) -> b)); //Working

why String.valueOf(entry.getKey()), entry.getValue() does not work even though its biFunctional?

    Map<String, String> map2 = inMap.entrySet().stream().collect(Collectors.toMap(entry -> String.valueOf(entry.getKey()), entry.getValue()));  //

Because entry.getValue() is not a Function but entry -> entry.getValue() is.

Map<String, String> map = inMap.entrySet()
                               .stream()
                               .collect(Collectors.toMap(entry -> String.valueOf(entry.getKey()), entry -> entry.getValue()); // should work

Or you could simply use forEach as:

Map<String, String> outMap = new HashMap<>();
inMap.forEach((k, v) -> outMap.put(k.toString(), v));

You can also use toString() Because in all wrapper classes toString() is overridden to return value

 Map<String, String> collect = inMap.entrySet()
                                    .stream()
                                    .collect(Collectors.toMap(entry->entry.getKey().toString(), Entry::getValue));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM