I am trying to achieve the following scenario.
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.
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With