Having a data map as below :
Map<String, List<Integer>> dataMap = ....
i want to convert it to another Map
below, the solution I've tried
Map<String, int[]> dataMapOut = new HashMap<>();
dataMap.entrySet().stream().forEach(entry -> {
String key = entry.getKey();
int[] val = entry.getValue().stream().mapToInt(i -> i).toArray();
dataMapOut.put(key, val);
});
Looking for better and more concise way of mapping ?
You're looking for the toMap collector.
Map<String, int[]> result = dataMap.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue()
.stream()
.mapToInt(Integer::intValue)
.toArray()));
With streams, use Collectors.toMap and Arrays.setAll to create the array from each List:
Map<String, int[]> dataMapOut = dataMap.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> {
int[] arr = new int[e.getValue().size()];
Arrays.setAll(arr, e.getValue()::get);
return arr;
}));
Without streams, using Map.forEach along with Arrays.setAll:
Map<String, int[]> dataMapOut = new HashMap<>();
dataMap.forEach((k, v) -> {
int[] arr = new int[v.size()];
Arrays.setAll(arr, v::get);
dataMapOut.put(k, arr);
});
Or, if you want to be succinct:
Map<String, int[]> map = new HashMap<>();
dataMap.forEach((k, v) -> map.put(k, v.stream().mapToInt(i -> i).toArray()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With