3

I have two lists

List1 - (1, 2, 3)
List2 - (4, 5, 6,7, 8)

Want to merge both the list as (1, 4, 2, 5, 3, 6, 7, 8) using java streams

First element from List1, List2 and, Second element from list1, list2 ...so on..if any extra elements remain then place at the end.

Naman
  • 27,789
  • 26
  • 218
  • 353
user3125890
  • 41
  • 1
  • 1
  • 4

3 Answers3

11
Stream.concat(list1.stream(), list2.stream())
   .collect(Collectors.toList())
Maxim Popov
  • 1,167
  • 5
  • 9
  • Maxim - thanks for the response but that will print as 1,2,3,4,5,6,7,8 means all from stream1 then stream2 but required as first element from list1, list2 and, second element from list1, list2 ...so on..if any extra elements ..then place at the end. – user3125890 Feb 17 '20 at 19:44
  • 2
    Oh, my fault. Sorry. Please look through this answer https://stackoverflow.com/a/51385350/6075655 – Maxim Popov Feb 17 '20 at 19:49
0

Other answer has a link to a working solution, but here's another approach:

    List<Integer> l1 = Arrays.asList(1, 2, 3);
    List<Integer> l2 = Arrays.asList(4, 5, 6, 7, 8);

    List<Integer> combined = IntStream.range(0, Math.max(l1.size(), l2.size()))
            .boxed()
            .flatMap(i -> {
                if (i < Math.min(l1.size(), l2.size()))
                    return Stream.of(l1.get(i), l2.get(i));
                else if (i < l1.size())
                    return Stream.of(l1.get(i));
                return Stream.of(l2.get(i));
            })
            .collect(Collectors.toList());

    System.out.println(combined);
Andrew S
  • 2,509
  • 1
  • 12
  • 14
-4

using java streams you can do it easily. List1.stream().collect(Collectors.toList()).addAll(List2);

Konzern
  • 110
  • 10