Java 11 Lambda – 检查每个对象,当满足第一个条件时返回true,否则返回false。

huangapple go评论73阅读模式
英文:

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>



huangapple
  • 本文由 发表于 2020年10月16日 07:57:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64381172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定