Home > OS >  Inline function filling an array
Inline function filling an array

Time:10-28

Is there any way to declare and populate an array in Java using an inline function/lambda like seen below?

final int NUM_NAMES = 10;
String names = () -> {
    ArrayList<String> names = new ArrayList();
    for (int i = 0; i < NUM_NAMES; i  ) {
        names.add("Name "   i);
    }
    return names.toArray();
};

CodePudding user response:

You could use the following:

List<String> names = IntStream.range(0, 10)
    .boxed()
    .map(i -> String.format("Name %d", i))
    .collect(Collectors.toList())

Hopefully syntax is fine there but you get the idea.

CodePudding user response:

You technically can do this inline, but the syntax is quite verbose:

String[] names = ((Supplier<String[]>)() -> {
  ArrayList<String> namesList = new ArrayList<>();
  for (int i = 0; i < NUM_NAMES; i  ) {
    namesList.add("Name "   i);
  }
  return namesList.toArray(new String[0]);
}).get();

so I wouldn't recommend it. You would have to specify the type of the lambda expression, cast to that type, and then put the whole cast expression in brackets so that you can call get to get the array that is produced.

A more concise way to initialise arrays inline would be a helper method like this (this is inspired by Kotlin's array constructors):

public static <T> T[] buildArray(T[] arr, IntFunction<T> elementFunction) {
    for (int i = 0 ; i < arr.length ; i  ) {
      arr[i] = elementFunction.apply(i);
    }
    return arr;
}

In the second parameter, you specify what element you want for each index:

String[] names = buildArray(new String[NUM_NAMES], i -> "Name "   i);

CodePudding user response:

Possibly the shortest way is to use Arrays.setAll which can be used to set values in arrays of any type, along with a index value generator to determine each indexed value:

String[] names = new String[NUM_NAMES];
Arrays.setAll(names, i -> "Name "   i);

Unfortunately Arrays.setAll does not return the array so you cannot put the whole declaration of names in one line.

  • Related