Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 streams - use original streamed object along the stream action

I am running Stream operations on an array of Integers.
I then create a Cell object that does some manipulations and apply a filter,
and I want to create a map of Integer to Cell with only the valid Cells.

Something along this line:

List<Integer> type = new ArrayList<>();

Map<Integer, Cell> map =
  list.stream()
    .map(x -> new Cell(x+1, x+2))        // Some kind of Manipulations
    .filter(cell->isNewCellValid(cell))  // filter some
    .collect(Collectors.toMap(....));

Is it possible to use original streamed object along the stream action?

like image 219
Bick Avatar asked Sep 12 '25 09:09

Bick


1 Answers

You can store the original Stream element if your map operation creates some instance that contains it.

For example:

Map<Integer, Cell> map =
  list.stream()
      .map(x -> new SomeContainerClass(x,new Cell(x+1, x+2)))
      .filter(container->isNewCellValid(container.getCell()))
      .collect(Collectors.toMap(c->c.getIndex(),c->c.getCell()));

There are some existing classes you can use instead of creating your own SomeContainerClass, such as AbstractMap.SimpleEntry:

Map<Integer, Cell> map =
  list.stream()
      .map(x -> new AbstractMap.SimpleEntry<Integer,Cell>(x,new Cell(x+1, x+2)))
      .filter(e->isNewCellValid(e.getValue()))
      .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
like image 131
Eran Avatar answered Sep 14 '25 01:09

Eran