Multiply the appearance of each item in the list by 4

I am trying to execute the following script.

enter image description here

I have an oldList and I'm trying to multiply the occurrences of each element by 4 and put them in a newList using the Stream API. The size of oldList is unknown, and each time it can be displayed with a different size.

I already solved this problem with two traditional loops as follows:

 private List< Integer > mapHourlyToQuarterlyBased( final List< Integer > oldList ) { List< Integer > newList = new ArrayList<>(); for( Integer integer : oldList ) { for( int i = 0; i < 4; i++ ) { newList.add( integer ); } } return newList; } 

but I recently learned the Stream API and would like to use it to consolidate my knowledge.

+6
source share
2 answers

You can use flatMap to create a Stream of 4 elements from each element of the original List , and then generate one Stream all these elements.

 List<Integer> mapHourlyToQuarterlyBased = oldList.stream() .flatMap(i -> Collections.nCopies(4, i).stream()) .collect(Collectors.toList()); 
+16
source

You can achieve using flatMap :

 List<Integer> result = list.stream().flatMap(i -> Stream.of(i,i,i,i)).collect(Collectors.toList()); 

or more generally:

 List<Integer> result = list.stream().flatMap(i -> Stream.generate(() -> i).limit(4)).collect(Collectors.toList()); 

For each element in the input list, a stream is created consisting of this element, which is repeated 4 times, and flat ones display it. Then all the items are collected in a list.

+10
source

All Articles