Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 use it to consolidate my knowledge.

like image 963
Ad Infinitum Avatar asked Aug 16 '16 10:08

Ad Infinitum


People also ask

How do you multiply each element of a list by a number in Python?

We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

Can you multiply lists in Python?

Lists and strings have a lot in common. They are both sequences and, like pythons, they get longer as you feed them. Like a string, we can concatenate and multiply a Python list.

How many elements can you store in a list?

1) Yes, list can store 100000+ elements. The maximum capacity of an List is limited only by the amount of memory the JVM has available.


1 Answers

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());
like image 182
Eran Avatar answered Oct 08 '22 08:10

Eran