0

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

1

1 Answer 1

2
var allObjectNames = allObjects.stream().map(o -> o.name).collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

3 Comments

o can not be resolved to a variable?
You should add a description not only code
fixed the typo in the code. @ImkerWarze try -> instead of the =>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.