D
D
Dmitry072017-05-17 16:58:05
Java
Dmitry07, 2017-05-17 16:58:05

How to put pairs of values ​​in a Map?

Good day.
As part of saving data, the following question arose: if there are value pairs in a format List<Object[]>with a repeated first element
101 - 201
101 - 202
101 - 203
102 - 204
102 - 205
102 - 206
103 - 207
103 - 208
103 - 209
As, say, technically is it correct to place this content within the framework Map<Integer, List<Integer>>, grouping the second elements into a list according to the similar first?
Thanks to.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Cr2ed, 2017-05-17
@Cr2ed

For each pair, you need the following code:

Map<Integer, List<Integer>> = new HashMap();

if (!map.contains(key)) {
    map.put(key, new ArrayList<Integer>())
}
map.get(key).put(value)

J
jumb0jet, 2017-05-17
@jumb0jet

Map<Integer, List<Integer>> groupingBy = list.stream()
                .collect(
                        groupingBy(
                                pair-> (Integer) pair[0],
                                mapping(
                                        pair-> (Integer) pair[1],
                                        toList()
                                )
                        )
                );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question