[Solved] Java 8 stream api code to add a element to a List based on condition keeping the list size same


You can achieve this by doing the following:

alist.stream()
    .flatMap(i -> i == 0 ? Stream.of(i, 0) : Stream.of(i))
    .limit(alist.size())
    .collect(Collectors.toList());

This basically:

  1. flatmaps your integer to a stream of itself if non-zero, and a stream of itself and an additional zero if equal to zero
  2. limits the size of your list to the original size

If this helped, you can accept this answer.

0

solved Java 8 stream api code to add a element to a List based on condition keeping the list size same