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

huangapple go评论82阅读模式
英文:

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&lt;DeviceFeature&gt; getAllEnabledFeatures(DeviceID deviceId){
	List&lt;String&gt; featureNames =  getAllEnabledDeviceFeatures(deviceId);
	List&lt;DeviceFeature&gt; featureList = new ArrayList&lt;&gt;();

	featureNames.forEach(featureName -&gt; {
		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 -&gt; 
                getDeviceFeatureEnabledForDevice(featureName, deviceId))
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年5月4日 19:25:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/61591104.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定