【问题标题】:How can i simplify this我怎样才能简化这个
【发布时间】:2021-04-17 13:52:44
【问题描述】:

有什么办法可以简化这段代码吗?我正好有 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");

【问题讨论】:

    标签: java java-stream refactoring simplify


    【解决方案1】:

    假设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);
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2019-11-10
      相关资源
      最近更新 更多