1

I have a List<List<Integer>> like this :

[
 [3, 12, 1, 14, 10],
 [3, 12, 1, 15, 10],
 [3, 13, 1, 12, 10],
 [3, 13, 1, 15, 10]
]

I would like something like this : (the first element is just 3 because in the previous list 3 is always at first place. The second element is [12,13] because on the previous list 12 and 13 are on the second index etc...)

[[3, [12,13], [1], [12,14,15], [10]]

A Map<Integer, List<Integer>> is also a valuable option

Is it possible with Java streams to do that ?

2
  • I would not recommend to solve this problem with streams. Reason is that we need to process elements in order and that is not guaranteed when working with streams. There are ways around this, but those make the solution more complex. Commented Aug 9, 2021 at 20:06
  • Your output doesn't look like a Map<Integer, List<Integer>>. Its rather a Collection<Set<Integer>> in the manner you have posted. Commented Aug 10, 2021 at 2:29

1 Answer 1

1

Is this what you had in mind? This presumes all the inner lists are of the same size.

List<List<Integer>> lists = List.of(
List.of(3, 12, 1, 14, 10),
List.of(3, 12, 1, 15, 10),
List.of(3, 13, 1, 12, 10),
List.of(3, 13, 1, 15, 10));
  • Stream the indices of the inner lists
  • for each of those lists in a stream, map the value at the index. Don't repeat values by using distinct.
  • collect those in a list
  • and collect the lists in a list.
List<List<Integer>> result = IntStream.range(0,5)
        .mapToObj(i->lists.stream()
                .map(lst->lst.get(i))
                .distinct().toList())
        .toList();
System.out.println(result);

Prints

[[3], [12, 13], [1], [14, 15, 12], [10]]

Note that the fourth list is not sorted but in the order in which the values were encountered. That can be fixed if required.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.