javaq
javaq

Reputation: 131

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 ?

Upvotes: 3

Views: 1056

Answers (3)

Hadi
Hadi

Reputation: 17299

Another solution can be like this:

Map<String,int[]> result= map.entrySet()
        .stream()
        .map(m->new AbstractMap.SimpleImmutableEntry<>(m.getKey(),m.getValue()
                   .stream()
                   .mapToInt(Integer::intValue)
                   .toArray()))
        .collect(Collectors.toMap(Map.Entry::getKey,entry->entry.getValue(),(e1,e2)->e1,LinkedHashMap::new));

Upvotes: 1

fps
fps

Reputation: 34460

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()));

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56453

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()));

Upvotes: 10

Related Questions