繁体   English   中英

我怎样才能简化这个

[英]How can i simplify this

有什么办法可以简化这段代码吗? 我正好有 1 块白色的,想要得到它的 position

代码:

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

瓷砖 class:

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

件 class:

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

假设boardTile对象的集合,第一个“白色”棋子可能如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM