Home > Software engineering >  Java map function
Java map function

Time:01-13

I want to use the map function (or stream function ?) to make this code this tighter.

var allObjectNames = new ArrayList<String>();
for (Object object : allObjects) {
     allObjectNames.add(object.name);
}

I thought about:

var allObjectNames = new ArrayList<String>();
allObjectsNames.addAll(map(allObjects.name));

Or something like this.

Minimalistic Example:

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

CodePudding user response:

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