-5

Is there any way i can simplify this code? I have exactly 1 white piece and want to get its position

Code:

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

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

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");
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
TimSom
  • 11
  • 1

1 Answers1

0

Assuming the board is collection of Tile objects, the first "white" piece may be found as this:

// Collection<Tile> board
Tile white = board.stream()
    .filter(tile -> tile.getPiece() != null && "white".equals(tile.getPiece().getType()))
    .findFirst() // Optional<Tile>
    .orElse(null);

Or Optional::map may be used to find the white piece:

Tile white = board.stream()
    .filter(tile -> Optional.ofNullable(tile.getPiece())
                        .map(piece -> "white".equals(piece.getType()))
                        .orElse(Boolean.FALSE))
    .findFirst() // Optional<Tile>
    .orElse(null);
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42