简体   繁体   English

Java 8流-在流操作中使用原始流对象

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

I am running Stream operations on an array of Integer s. 我在Integer数组上运行Stream操作。
I then create a Cell object that does some manipulations and apply a filter, 然后,我创建一个Cell对象,该对象进行一些操作并应用过滤器,
and I want to create a map of Integer to Cell with only the valid Cell s. 我想只用有效的Cell创建一个IntegerCell的映射。

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. 如果您的map操作创建了包含它的实例,则可以存储原始Stream元素。

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 : 您可以使用一些现有的类来代替创建自己的SomeContainerClass ,例如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));

Is it possible to use original streamed object along the stream action? 是否可以在流操作中使用原始流对象?

Yes, until you don't use a map operation. 是的,直到您不使用map操作。

You need a Function<Cell, Integer> to restore an original value. 您需要一个Function<Cell, Integer>来恢复原始值。 In your example, it is (Cell cell) -> cell.getFirst() - 1 : 在您的示例中,它是(Cell cell) -> cell.getFirst() - 1

.collect(Collectors.toMap(cell -> cell.getFirst() - 1, Function.identity()));

I suggest writing Function<Integer, Cell> and Function<Cell, Integer> functions and not building unnecessary wrapper classes for a single stream process: 我建议编写Function<Integer, Cell>Function<Cell, Integer>函数,不要为单个流进程构建不必要的包装器类:

final Function<Integer, Cell> xToCell = x -> new Cell(x + 1, x + 2);
final Function<Cell, Integer> cellToX = cell -> cell.getX1() - 1;

final Map<Integer, Cell> map =
        list
                .stream()
                .map(xToCell)
                .filter(cell -> isNewCellValid(cell))
                .collect(Collectors.toMap(cellToX, Function.identity()));

Of course, it's efficient for the operations that can be simply or intuitively inverted. 当然,对于可以简单地或直观地反转的操作,它是高效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM