Ad Infinitum Ad Infinitum - 1 year ago 71
Java Question

Multiply the occurence of each element in a list by 4

I am trying to achieve the following scenario.

enter image description here

I have an

and I am trying to multiply the occurences of each element by 4 and put them in a
by using the Stream API. The size of the oldList is not known and each time, it may appear with a different size.

I have 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 have learnt the Stream API newly and would like to consolidate my knowledge.

Answer Source

You could use a flatMap to produce a Stream of 4 elements from each element of the original List and then generate a single Stream of all these elements.

List<Integer> mapHourlyToQuarterlyBased =
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download