John Baum
John Baum

Reputation: 3331

Using a function in Java8 map

Is there a Java8 equivalent way of writing the following?

List<Foo> results = new ArrayList<>();
for (RowResult row : rows) {
   results.add(rowToFooFunction(classroomLookup.get(row.getId()), studentLookup.get(row.getId())).apply(row));
}

Where the rowToFooFunction is like Function<RowResult, Foo> rowToFoo (Classroom c, Student s)...

So I would like to end up with something like:

rows.stream.map(rowToFooFunction...).collect(Collectors.toList());

The problem is, in the map step, I need to lookup the student/classroom by the id of the row i am iterating over.

Upvotes: 1

Views: 94

Answers (1)

sebnukem
sebnukem

Reputation: 8333

You almost found the solution yourself already, you are very close:

List<Foo> results = rows.stream().map(row ->
  rowToFooFunction(classroomLookup.get(row.getId()), studentLookup.get(row.getId())).apply(row))
).collect(Collectors.toList());

Upvotes: 3

Related Questions