Search code examples
javajava-stream

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


Consider i have below list

List<Integer> alist = new ArrayList<>(); 
          list=Arrays.asList(0,1,2,0,4,10);
          
          alist.addAll(list);

I want the output as 0 0 1 2 0 0.

That means if there is a zero in the list add one more zero in list. Do this untill the size of list is same as input size.

How can this be done using Java 8 stream api?


Solution

  • 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