Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.fill(int)(method()) equivalent in Java?

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 fors 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.

like image 417
m482 Avatar asked Jan 29 '16 13:01

m482


2 Answers

There is an equivalent with Java 8 :

  • Use a Stream to generate a sequence
  • For each value of the sequence, map it using whichever method you want
  • Collect the result

Example :

List<Result> collect = IntStream.range(0, 5)
                      .mapToObj(i -> doSomething(i))
                      .collect(Collectors.toList());

public Result doSomething(Integer i) {
  return ...;
}
like image 198
Arnaud Denoyelle Avatar answered Oct 26 '22 02:10

Arnaud Denoyelle


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.

like image 44
som-snytt Avatar answered Oct 26 '22 04:10

som-snytt