我可以使用流来创建一个列表,其中的标准是检查一个列表,然后将一个对象添加到另一个列表中吗?

问题描述 投票:0回答:1

在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;
}
java java-8 stream
1个回答
5
投票

你不需要 forEach列表,你可以直接创建一个列表,通过映射 featureNames:

return  getAllEnabledDeviceFeatures(deviceId)
        .stream()
        .map(featureName -> 
                getDeviceFeatureEnabledForDevice(featureName, deviceId))
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.