1

我最近开始使用 retrolambda 库来支持 android 开发中的 lambda,我收到了来自 Android Studio 的以下警告:

可以用对方付费电话代替。

此检查报告可以用流 api 调用替换的 foreach 循环。

我的代码如下:

// mGeofenceList is a List<Geofence>
mGeofenceList = new ArrayList<>();
    // GeofenceUtils.GeofenceObjects.entrySet() is a HashMap<String, LatLng>
    for (Map.Entry<String, LatLng> entry : GeofenceUtils.GeofenceObjects.entrySet()) {
        mGeofenceList.add(new Geofence.Builder()
                .setRequestId(entry.getKey())
                .setCircularRegion(
                        entry.getValue().latitude,
                        entry.getValue().longitude,
                        GeofenceUtils.GEOFENCE_RADIUS_IN_METERS)
                .setExpirationDuration(GeofenceUtils.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                        Geofence.GEOFENCE_TRANSITION_EXIT)
                .build());
    }

问题:如何将其替换为对方付费电话?

更新:当我按下 alt+enter 时,它会将代码转换为以下内容:

// method stream() cannot be found    
mGeofenceList.addAll(GeofenceUtils.GeofenceObjects.entrySet().stream()
            .map(entry -> new Geofence.Builder()
            .setRequestId(entry.getKey())
            .setCircularRegion(
                    entry.getValue().latitude,
                    entry.getValue().longitude,
                    GeofenceUtils.GEOFENCE_RADIUS_IN_METERS)
            .setExpirationDuration(GeofenceUtils.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                    Geofence.GEOFENCE_TRANSITION_EXIT)
            // Collectors cannot be found
            .build()).collect(java.util.stream.Collectors.toList()));

现在它说它无法解析方法流(),收集器。它可以修复吗?我可以添加一些导入语句吗?还是目前retrolambda不支持?

更新:已解决,请参阅下面的答案。

4

1 回答 1

2

感谢所有在问题下发表评论的人。在这个库的帮助下解决了这个问题:https ://github.com/aNNiMON/Lightweight-Stream-API

Stream.of(YourCollection) 在 Java 8 实现中,您将看到 YourCollection.stream(...) 。无论哪种方式,都会创建 Stream 的实例。

这个库的最终工作代码:

// stream() changed to Stream.of( ... ) as per library specs
mGeofenceList.addAll(Stream.of(GeofenceUtils.GeofenceObjects.entrySet())
                .map(entry -> new Geofence.Builder()
                .setRequestId(entry.getKey())
                .setCircularRegion(
                        entry.getValue().latitude,
                        entry.getValue().longitude,
                        GeofenceUtils.GEOFENCE_RADIUS_IN_METERS)
               .setExpirationDuration(GeofenceUtils.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
               .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)

               // Collectors works without prefix
               .build()).collect(Collectors.toList()));
于 2016-04-05T05:33:58.820 回答