我想使用map函数(或者stream函数?)来使代码更紧凑。
var allObjectNames = new ArrayList<String>();
for (Object object : allObjects) {
allObjectNames.add(object.name);
}
我想过:
var allObjectNames = new ArrayList<String>();
allObjectsNames.addAll(map(allObjects.name));
或者类似的东西。
极简主义示例:
package Mapping;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FunctionMapping {
public static void main(String[] args) {
var output1 = new Output("start");
var output2 = new Output("success");
var output3 = new Output("failure");
ArrayList<Output> rootOutput = new ArrayList<>();
rootOutput.add(output1);
rootOutput.add(output2);
rootOutput.add(output3);
var outputNames = rootOutput.stream().map(o -> o.outputName).collect(Collectors.toList());
}
static class Output {
String outputName;
Output (String name) {
this.outputName = name;
}
}
}
1条答案
按热度按时间axr492tv1#