簡體   English   中英

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

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

我在Integer數組上運行Stream操作。
然后,我創建一個Cell對象,該對象進行一些操作並應用過濾器,
我想只用有效的Cell創建一個IntegerCell的映射。

這句話:

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

是否可以在流操作中使用原始流對象?

如果您的map操作創建了包含它的實例,則可以存儲原始Stream元素。

例如:

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

您可以使用一些現有的類來代替創建自己的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));

是否可以在流操作中使用原始流對象?

是的,直到您不使用map操作。

您需要一個Function<Cell, Integer>來恢復原始值。 在您的示例中,它是(Cell cell) -> cell.getFirst() - 1

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

我建議編寫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()));

當然,對於可以簡單地或直觀地反轉的操作,它是高效的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM