您可以应用filter()
,并将嵌套流(exactly the same as you've used as a condition in your code)作为Predicate
传递给它,以验证列表仅包含non-empty个图块.
然后使用collect()
收集已将predicate传递到列表中的所有列表(rows).
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
当您的目标是将集合流(or objects holding a reference to a collection)扁平化为这些集合的元素流时,需要使用flatMap
.在这种情况下,将瓷砖列表流Stream<List<Tile>>
转变为瓷砖流Stream<Tile>
.
从你的代码判断,这不是你想要的,因为你正在将rows个(瓷砖列表)累积到另一个列表中,而不是"flattening"个.
但以防万一,这就是如何做到的:
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+
}
Sidenote:利用抽象数据类型-根据接口编写代码.What does it mean to "program to an interface"?