-1

I have an integer array int[] and would like to create an List of entries that contains:

class Entry {
   int theIndexOfNumber;
   int numberInTheArray;
}

For example, for {3,5,7}, I would like to have a list of

{1, 3}, {2, 5},(3, 7}

This is easy using some Java code but I want to do it in a Java 8 way using stream.

I think I should use some sort of collector but don't know how to write this. Can someone please help?

Eran
  • 387,369
  • 54
  • 702
  • 768
ZZZ
  • 645
  • 4
  • 17
  • 2
    `IntStream.range(0, array.length) .mapToObj(i -> new Entry(i + 1, array[i])) .collect(Collectors.toList());` – Hadi J Apr 17 '19 at 09:05

1 Answers1

2

You can iterate over the indices of the array using an IntStream and map each index to the corresponding Entry instance:

int[] arr = ...
List<Entry> entries =
    IntStream.range(0,arr.length)
             .mapToObj(i -> new Entry(i+1,arr[i]))
             .collect(Collectors.toList());

This is assuming Entry has the required constructor.

Eran
  • 387,369
  • 54
  • 702
  • 768