1

Is there a better way to convert a Map<String, List<String>> to Map<String, Object[]> or vice versa other than a for loop? By better, I mean using any library or Lambda expressions

4
  • 3
    Please define "better" in the context of your requirements. Commented Aug 26, 2015 at 20:27
  • stackoverflow.com/questions/9572795/… Commented Aug 26, 2015 at 20:27
  • 2
    Thank you for editing your question. Can you now show what you have tried and describe why it doesn't achieve what you want? And have you done any research (like reading stackoverflow.com/q/22742974/1945631 and stackoverflow.com/q/9572795/1945631)? Commented Aug 26, 2015 at 20:29
  • I have used the link provided by you to form an answer. I have posted the answer for this. I was wondering if this can be further improved? Commented Aug 26, 2015 at 21:33

2 Answers 2

2

I tried this way as mentioned in In Java 8 how do I transform a Map to another Map using a lambda?

final Map<String, List<String>> listMap = new HashMap<>();
listMap.put("Dog", Arrays.asList("Boxer","Julie"));
listMap.put("Cat", Arrays.asList("Cat1","Cat2"));

Map<String,Object[]> objectMap = listMap.entrySet().stream()
    .collect(Collectors.toMap(e->e.getKey(), e->e.getValue().toArray()));

This worked. Is there any issue with this code or can it be further improved?

Sign up to request clarification or add additional context in comments.

Comments

0

It is possible to create a custom Map class that overrides the appropriate methods in the java.util.Map interface to handle "lazy" conversions.

Such a class would be initialized with the Map<String, List<String>> or Map<String, Object[]> object and operate as a native Map<String, Object[]> or Map<String, List<String>>, respectively.

Comments

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.