Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Map<String, List<Integer>> to Map<String, int[]>

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 ?

like image 754
javaq Avatar asked May 14 '26 06:05

javaq


2 Answers

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()));
like image 51
Ousmane D. Avatar answered May 15 '26 20:05

Ousmane D.


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()));
like image 22
fps Avatar answered May 15 '26 22:05

fps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!