英文:
Can I create a list using streams where the critera are to check one list then add an object to another list?
问题
使用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;
}
(Note: The code is provided as is, without translation, as per your request.)
英文:
Is there a more elegant way to do this using streams, in java 8?
Can you give me some tips on what parts of the documentation I should look at?
I thought it might be possible to do this without creating the empty featureList
first, but I can't get it to work.
There are two levels of features here, generic features that are available across all devices, and features that are enabled specifically on this device, since even though they are available, they can switched off for specific devices if we desire.
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;
}
答案1
得分: 4
不需要使用forEach
,可以通过对featureNames
进行映射直接创建一个列表:
return getAllEnabledDeviceFeatures(deviceId)
.stream()
.map(featureName ->
getDeviceFeatureEnabledForDevice(featureName, deviceId))
.filter(Objects::nonNull)
.collect(Collectors.toList());
英文:
You don't need forEach
, you can create a list directly by mapping featureNames
:
return getAllEnabledDeviceFeatures(deviceId)
.stream()
.map(featureName ->
getDeviceFeatureEnabledForDevice(featureName, deviceId))
.filter(Objects::nonNull)
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论