Java Lambda to convert an Object[] array to a subset Object[] array

Viewed 103

I have an initial array, array1 which contains 30 elements and need to create a new array array2 containing elements 0-14 from array1.

I'm using IntStream as the mapper for the array index. But the following gives errors:

Object[] array2 = IntStream.range(0,14).map(x -> (Object)array1[x]).toArray(Object[]::new);

Error on (Object)array1[x]:

The type of the expression must be an array type but it resolved to List<Object[]>
3 Answers

In your example, x is a type of integer. You should use the .mapToObj instead map method.

Object[] array2 = IntStream.range(0, 14)
        .mapToObj(x -> array1[x])
        .toArray(Object[]::new);

You can also use Arrays.copyOfRange() instead of Stream.

Object[] array2 = Arrays.copyOfRange(array1, 0, 14);

To get first 15 (0-14) elements from an array to an array

List<String> first15ElementsList = Arrays.stream(arr)
.limit(15)
.collect(Collectors.toList());
Related