Roxy Roxy - 15 days ago 6
Java Question

How to convert a List of one type to a List of another type using Streams?

I want to use Streams to achieve the following:

I have list of

Input
and
Output
objects having a completely different structure.

With a for loop I can transform the
List<Input>
to a
List<Output>
as follows :

for(Input input :listOfInput) {
Output currentOutPutInstance = new Output();
currentOutPutInstance.setArg1(input.getArg2());
currentOutPutInstance.setArg2(input.getArg7());
listOfOutPuts.add(currentOutPutInstance);
}


With streams I tried something like this :

private List<Output> getOutPutListFromInputList(List<Input> inPutList) {
List<Output> outPutList=new ArrayList<Output>();
outPutList= listOfPoolsInRun.stream.filter(// Somehow converting the input into output).collect(Collectors.toList());
}


Note: I am not sure which function it would be . I have used filter just to show some dummy code.

Please help me with this.

Thanks

Answer

Use a map to transform a Stream<Input> to a Stream<Output> :

private List<Output> getOutPutListFromInputList(List<Input> inPutList){
    return listOfPoolsInRun.stream()
                           .map(input -> {
                                Output out = new Output();
                                out.setArg1(input.getArg2());
                                out.setArg2(input.getArg7());
                                return out;
                            })
                           .collect(Collectors.toList()); 
}

This could be made shorter if you have the appropriate constructor in the Output class :

private List<Output> getOutPutListFromInputList(List<Input> inPutList){
    return listOfPoolsInRun.stream()
                           .map(input -> new Output(input.getArg2(),input.getArg7()))
                           .collect(Collectors.toList()); 
}