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

  • 3
    Please define "*better*" in the context of your requirements. – Andy Brown Aug 26 '15 at 20:27
  • http://stackoverflow.com/questions/9572795/convert-list-to-array-in-java – Blake Yarbrough Aug 26 '15 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 http://stackoverflow.com/q/22742974/1945631 and http://stackoverflow.com/q/9572795/1945631)? – Andy Brown Aug 26 '15 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? – Satyanand Kale Aug 26 '15 at 21:33

2 Answers2

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?

Community
  • 1
  • 1
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.

PNS
  • 17,431
  • 26
  • 86
  • 131