0

I have a method that works fine. This is how it looks.

private boolean roomWithMoreThanTenFurnitures(Building building) {
if (building != null && building.hasRooms()) {
    for (Room room : building.getRooms()) {
        if (room.getFurnitures.size() > 10) {
            return true;
        }
    }   
}
return false;
}

I wanna switch this to Lambda. In came uo with the shell, but I am not sure how fill in the if (condition) return true or return false outside.

building.getRooms().forEach(room -> {
//??
});
Trozan
  • 89
  • 2
  • 11

2 Answers2

5

You cannot do it this way - the foreach is for executing some action for every of the collection/stream element not for filtering them or mapping to a result

You need e.g. anyMatch method - for example

building.getRooms().stream().anyMatch(room -> room.getFurnitures.size() > 10)
m.antkowicz
  • 13,268
  • 18
  • 37
0

You can do it like this. Returns false based on the initial conditions, then streams the rooms. This presumes the rooms can be streamed (e.g a List). If they are an array you will need to do something similar to Arrays.stream(building.getRooms())

private boolean roomWithMoreThanTenFurnitures(Building building) {
    if (building != null && building.hasRooms()) {
        return building.getRooms().stream()
                .anyMatch(room -> room.getFurnitures.size() > 10);
                
    }
    return false;
}
WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    Or just `return building != null && building.hasRooms() && building.getRooms().stream() .anyMatch(room -> room.getFurnitures.size() > 10);` – Holger Oct 16 '20 at 08:04