英文:
Java 11 Lambda - check each object, return true when the first condition is met, else return false
问题
我有一个运行良好的方法。它的外观如下。
private boolean roomWithMoreThanTenFurnitures(Building building) {
if (building != null && building.hasRooms()) {
for (Room room : building.getRooms()) {
if (room.getFurnitures().size() > 10) {
return true;
}
}
}
return false;
}
我想将其转换为Lambda表达式。我已经创建了外壳,但不确定如何在if (condition)
之后填入return true
或在外部填入return false
。
building.getRooms().forEach(room -> {
// ??
});
英文:
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 -> {
//??
});
答案1
得分: 5
你不能用这种方式做 - foreach
用于对集合/流元素执行某些操作,而不是用于筛选它们或映射到结果。
你需要使用例如 anyMatch
方法 - 例如:
building.getRooms().stream().anyMatch(room -> room.getFurnitures().size() > 10)
英文:
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)
答案2
得分: 0
你可以这样做。根据初始条件返回false
,然后对房间进行流处理。这假设房间可以被流式处理(例如一个列表)。如果它们是数组,你需要类似这样的操作: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;
}
英文:
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;
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论