繁体   English   中英

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

[英]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;
}

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

return  getAllEnabledDeviceFeatures(deviceId)
        .stream()
        .map(featureName -> 
                getDeviceFeatureEnabledForDevice(featureName, deviceId))
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM