简体   繁体   中英

Convert a Map<String, List<String>> to Map<String, Object[]>

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

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?

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.

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