在java 8中,是否有更优雅的方法来使用流来实现?你能给我一些提示,让我看看文档中的哪些部分吗?我想也许可以在不创建空的 featureList
首先,但我不能让它工作。
这里有两个层次的功能,一个是所有设备都可以使用的通用功能,另一个是专门在这个设备上启用的功能,因为即使可以使用,但如果我们愿意,也可以为特定的设备关闭。
public List<DeviceFeature> getAllEnabledFeatures(DeviceID deviceId){
List<String> featureNames = getAllEnabledDeviceFeatures(deviceId);
List<DeviceFeature> featureList = new ArrayList<>();
featureNames.forEach(featureName -> {
DeviceFeature feature = getDeviceFeatureEnabledForDevice(featureName, deviceId);
if(feature != null) featureList.add(feature);
});
return featureList;
}
你不需要 forEach
列表,你可以直接创建一个列表,通过映射 featureNames
:
return getAllEnabledDeviceFeatures(deviceId)
.stream()
.map(featureName ->
getDeviceFeatureEnabledForDevice(featureName, deviceId))
.filter(Objects::nonNull)
.collect(Collectors.toList());