In Scala, there is a method that looks something like this.
List[(A, B)] = List.fill(n)(doSomething(arg))
My question is if there is any way to do this in Java, or if it would have to be done through a series of lengthy for
s and what have you.
Java does have Collections.fill
but it doesn't seem to do what I want it to do.
Scala implementation is as follows:
def buyCoffee(cc: CreditCard): (Coffee, Charge) =
{
val cup = new Coffee()
(cup, Charge(cc, cup.price))
}
def buyCoffees(cc: CreditCard, n: Int): (List[Coffee], Charge) =
{
val p: List[(Coffee, Charge)] = List.fill(n)(buyCoffee(cc))
}
This does not seem achievable in Java to me, or not from what I know of Java or what I have been able to find in the documentation thus far.
This Scala code can be found on Page 7 of Functional Programming in Scala by Paul Chiusana and Rúnar Bjarnason.
There is an equivalent with Java 8 :
Example :
List<Result> collect = IntStream.range(0, 5)
.mapToObj(i -> doSomething(i))
.collect(Collectors.toList());
public Result doSomething(Integer i) {
return ...;
}
There is a JEP for creating small collections or the issue is easier to read.
It shows a couple of idioms, one of which uses an initializer. A Java 8 version of fill
:
import java.util.*;
import java.util.function.*;
public class j {
public static <T> List<T> fill(int n, Function<Integer, T> f) {
return Collections.unmodifiableList(new ArrayList<T>(n) {{
for (int i = 0; i < n; i++) add(f.apply(i));
}});
}
public static void main(String[] args) {
List<Integer> values = fill(10, i -> 2 * i);
for (int x : values) System.out.println(x);
}
}
I haven't looked for a JEP for other conveniences, but it's clear that these API are on their minds.
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