如何在我的代码中仅使用 Streams 而不使用 for
来实现相同的逻辑?循环如我下面的代码所示?
我试过使用 flatMap
, 但我卡在了条件部分,因为 allMatch()
只返回 boolean
.
如何从嵌套的 ArrayList
中检索所有行在不使用 for
的情况下通过条件循环?
ArrayList<ArrayList<Tile>> completeRows = new ArrayList<>();
for (ArrayList<Tile> rows: getGridTiles()) {
if (rows.stream().allMatch(p -> p.getOccupiedBlockType() != BlockType.EMPTY)) {
completeRows.add(rows);
}
}
最佳答案
可以申请filter()
嵌套流(与您在代码中用作条件的完全相同)作为 Predicate
传递给它验证列表是否仅包含非空 block 。
然后使用collect()
将所有通过谓词 的列表(行)收集到列表中.
public static List<List<Tile>> getNonEmptyRows(List<List<Tile>> rows) {
return rows.stream()
.filter(row -> row.stream().allMatch(tile -> tile.getOccupiedBlockType() != BlockType.EMPTY))
.collect(Collectors.toList()); // or .toList() with Java 16+
}
I have tried using
flatMap
您需要使用 flatMap
当您的目标是将集合流(或持有集合引用的对象)扁平化为这些集合的元素流时。在这些情况下,将瓷砖列表流变为 Stream<List<Tile>>
进入瓷砖流Stream<Tile>
.
根据您的代码判断,这不是您想要的,因为您正在将行(图 block 列表)累积到另一个列表中,而不是“展平”它们。
但为了以防万一,可以这样做:
public static List<Tile> getNonEmptyTiles(List<List<Tile>> rows) {
return rows.stream()
.filter(row -> row.stream().allMatch(tile -> tile.getOccupiedBlockType() != BlockType.EMPTY))
.flatMap(List::stream)
.collect(Collectors.toList()); // or .toList() with Java 16+
}
旁注:利用抽象数据类型 - 针对接口(interface)编写代码。 What does it mean to "program to an interface"?
关于java - 如何使用 Stream 从嵌套列表中获取符合特定条件的所有列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73026511/