我如何在我的代码中实现相同的逻辑,只使用流,没有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
,以验证列表仅由非空块组成。
然后收集使用collect()
将谓词传递到List中的所有列表(行)。
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+
}
我试过使用
flatMap
当您的目标是将集合(或持有对集合引用的对象)的蒸汽平坦化为这些集合的元素流时,您需要使用flatMap
。在这种情况下,将包含瓷砖列表的流Stream<List<Tile>>
转换为包含瓷砖列表的流Stream<Tile>
。
从你的代码来看,这不是你想要的,因为你把行(瓷砖列表)累加到另一个列表中,而不是"平坦化">它们。
但为了以防万一,我们可以这样做:
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+
}
旁注:利用抽象数据类型-根据接口编写代码。"编程到接口"是什么意思?