Merge 3 Lists with special order after merging (using streams)

I want to combine 3 lists in Java 8 using Streams. Achieving this is not very difficult. The following code can do this:

List<IntVar> combined = Stream.of(listA, listB, listC).flatMap(Collection::stream).collect(Collectors.toList());

Now I have a requirement that the elements of a merged list are executed in a simple order. The premise is that all lists are the same size.

Present 3 lists of 4 items:

  • List A contains the elements a1 a2 a3 a4
  • List B contains the elements b1 b2 b3 b4
  • List C contains elements c1 c2 c3 c4

The items in a combo box should be in the following order:

a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4

I think you get the point. Is there a way to do this in Java 8 using Streams?

+4
1

( n), IntStream , for-loop:

List<String> x = Arrays.asList("a1", "a2", "a3");
List<String> y = Arrays.asList("b1", "b2", "b3");
List<String> z = Arrays.asList("c1", "c2", "c3");
int n = x.size();
List<String> list = new ArrayList<>();
IntStream.range(0, n)
         .boxed()
         .forEach(i -> { list.add(x.get(i)); 
                         list.add(y.get(i)); 
                         list.add(z.get(i)); 
                        });
+3

Source: https://habr.com/ru/post/1651756/


All Articles