John Baum John Baum - 3 months ago 12
Java Question

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.

Answer

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());
Comments