4

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()));  //
1
  • Because it's parsed as entry -> String.valueOf(entry.getKey()) and entry.getValue(). Commented Apr 15, 2019 at 2:36

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

Comments

3

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));

1 Comment

map2.put(k.toString(),v)); seems very much intuitive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.