我需要返回我需要在 forEach
中访问的某个对象的属性环形。基本上我有一个 user
具有 List<UserLocation>
属性的对象在 UserLocation
里面对象是 Location
属性为 location_id
的对象.如果store_id
在 user
上对象匹配 store_id
在 UserLocation
上对象,这是我需要得到 location_id
的对象从。但是,我得到的问题是它说 lambda 表达式中使用的变量应该是最终的或实际上是最终的。请参阅下面的代码。
User user = getUser(request);
Integer locationId;
user.getUserLocations().forEach(ul -> {
if (ul.getStoreId() == user.getStoreId()) {
locationId= ul.getUserLocations().getLocationId();
}
});
如有任何建议或解决方案,我们将不胜感激!
最佳答案
该错误准确地告诉您问题出在哪里:您不能从闭包内部赋值。您可以通过创建可变容器、数组或列表来解决此问题,但更好的方法是使用流的 findFirst
。方法:
Optional<Integer> optLocationId = user.getUserLocations().stream()
.filter(ul -> ul.getStoreId() == user.getStoreId())
.findFirst();
if (optLocationId.isPresent()) {
Integer locationId = optLocationId.get().getUserLocations().getLocationId();
}
关于Java 8 forEach 从内部循环返回属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44009357/