Ad Infinitum Ad Infinitum - 3 months ago 7
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

oldList
and I am trying to multiply the occurences of each element by 4 and put them in a
newList
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

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 =
    oldList.stream()
           .flatMap(i->Collections.nCopies(4,i).stream())
           .collect(Collectors.toList());
Comments