I am running Stream
operations on an array of Integer
s.
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 Cell
s.
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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With