简体   繁体   中英

Can I create a list using streams where the critera are to check one list then add an object to another list?

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;
}

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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