Java 8 forEach从内部循环

时间:2017-05-16 18:50:56

标签: java collections lambda

我需要在forEach循环中返回我需要访问的某个对象的属性。基本上我有user对象,其属性为List<UserLocation>UserLocation对象内部是Location对象,属性为location_id。如果store_id对象上的userstore_id对象上的UserLocation匹配,那么我需要从location_id获取User user = getUser(request); Integer locationId; user.getUserLocations().forEach(ul -> { if (ul.getStoreId() == user.getStoreId()) { locationId= ul.getUserLocations().getLocationId(); } }); 。但是,我得到的问题是它说lambda表达式中使用的变量应该是final或者有效的final。请参阅下面的代码。

<script src="https://cdn.airmap.io/map-sdk/1.2.1/dist/airmap.map.min.js"></script>
<script src="/js/airmap.config.json"></script>

<script>
  var map = new Airmap.Map(<<API KEY>>, {
    container: 'map',
    **center**: [27.9104234,-82.7700782],
    layers: [ 'airports_recreational', 'heliports', 'national_parks' ],
    theme: 'standard',
    **zoom**: 5.5,
    pitch: 0,
    bearing: 0,
    interactive: true,
    showControls: true,
    tileServiceUrl:"https://api.airmap.com/maps/v4/tilejson",
    webAppUrl:"https://app.airmap.io",
  });
</script>

任何建议或解决方案都将不胜感激!

2 个答案:

答案 0 :(得分:4)

错误告诉您问题究竟是什么:您无法从闭包内部进行分配。您可以通过创建可变容器,数组或列表来解决此问题,但更好的方法是使用流的findFirst方法:

Optional<Integer> optLocationId = user.getUserLocations().stream()
    .filter(ul -> ul.getStoreId() == user.getStoreId())
    .findFirst();
if (optLocationId.isPresent()) {
    Integer locationId = optLocationId.get().getUserLocations().getLocationId();
}

答案 1 :(得分:1)

假设您只需要找到一个位置,这可以在没有forEach的情况下更好地完成:

Integer locationId = user.getUserLocations()
                         .stream()
                         .filter(ul -> ul.getStoreId() == user.getStoreId())
                         .findAny()
                         .map(ul -> ul.getLocation().getLocationId())
                         .orElse (0); // default value in case no match is found

P.S。我假设ul.getUserLocations()是一个拼写错误,应该是ul.getLocation(),因为你写了inside the UserLocation object is a Location objectgetUserLocations()似乎是User类的方法,而不是UserLocation类。