JavaMap函数

piwo6bdm  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(152)

我想使用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;
        }
    }
    
}
axr492tv

axr492tv1#

var allObjectNames = allObjects.stream().map(o -> o.name).collect(Collectors.toList());

相关问题