-1

I have two lists as below:

List ids = Arrays.asList(1,2,3); List reps = Arrays.asList("abc","pqr","xyz");

Now I want to create list of Prediction objects with values mapped from above two lists in sequence like below:

List results = [ Prediction(1,"abc") , Prediction(2,"pqr"), Prediction(3,"xyz") ]

class Prediction {
    int id;
    String rep;
}

How this can be done using Java8 Stream API.

user3812288
  • 21
  • 1
  • 6

1 Answers1

1

The operation you described is called zipping.

If you are sure the lists are evenly of length, you could do something like:

IntStream.range(0, ids.size())
    .mapToObj(i -> new Prediction(ids.get(i), reps.get(i)))
    .toList()

Assuming the Prediction class has a constructor like that...

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78