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
-
3Please define "better" in the context of your requirements.Andy Brown– Andy Brown2015-08-26 20:27:26 +00:00Commented Aug 26, 2015 at 20:27
-
stackoverflow.com/questions/9572795/…Blake Yarbrough– Blake Yarbrough2015-08-26 20:27:44 +00:00Commented Aug 26, 2015 at 20:27
-
2Thank 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)?Andy Brown– Andy Brown2015-08-26 20:29:38 +00:00Commented 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?Satyanand Kale– Satyanand Kale2015-08-26 21:33:57 +00:00Commented Aug 26, 2015 at 21:33
Add a comment
|
2 Answers
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?
Comments
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.