如何解决我怎样才能简化这个
有什么办法可以简化这段代码吗?我正好有 1 个白色棋子,想要得到它的位置
代码:
final Tile[] white = {null};
board.forEach(tile -> {
Piece temp = tile.getPiece();
if (temp != null) {
if (temp.getType().equals("white")) { white[0] = tile; }
}
});
System.out.println(white[0].getX());
System.out.println(white[0].getY());
瓷砖类:
public class Tile {
private final StringProperty color = new SimpleStringProperty(this,"color");
private final IntegerProperty x = new SimpleIntegerProperty(this,"x");
private final IntegerProperty y = new SimpleIntegerProperty(this,"y");
private final BooleanProperty hasPiece = new SimpleBooleanProperty(this,"hasPiece");
private final BooleanProperty isMarked = new SimpleBooleanProperty(this,"isMarked");
private final ObjectProperty<Piece> piece = new SimpleObjectProperty<>(this,"piece");
件类:
public class Piece {
private final StringProperty type = new SimpleStringProperty(this,"type");
private final StringProperty imagePath = new SimpleStringProperty(this,"imagePath");
private final ObjectProperty<List<Coords>> possible_moves = new SimpleObjectProperty<>(this,"possible_moves");
解决方法
假设 board
是 Tile
对象的集合,第一个“白色”部分可能是这样的:
// Collection<Tile> board
Tile white = board.stream()
.filter(tile -> tile.getPiece() != null && "white".equals(tile.getPiece().getType()))
.findFirst() // Optional<Tile>
.orElse(null);
或者可以使用 Optional::map
来查找白色部分:
Tile white = board.stream()
.filter(tile -> Optional.ofNullable(tile.getPiece())
.map(piece -> "white".equals(piece.getType()))
.orElse(Boolean.FALSE))
.findFirst() // Optional<Tile>
.orElse(null);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。