skumar
skumar

Reputation: 1015

java8 stream collect different list

I want to convert the input list to different list after filter. Please let know how to implement in java8 stream.

I tried something like below, it gave compilation error "p cannot be resolved to a variable" in getOutput() in collect().

List<Output> outputList= inputList.stream()
                    .filter(p ->  p.param1==10)                     
                    .collect(Collectors.toList(getOutput(p)));  


private Output getOutput(Input inp){
 Output out = new Output();
 out.value1= inp.value1;
 ---
 ---
}

Upvotes: 0

Views: 4465

Answers (1)

george
george

Reputation: 3221

As suggested by the comments you can do something like this

List<Output> outputList= inputList.stream()
                    .filter(p ->  p.param1==10) 
                    .map(j -> getOutput(j))
                    .collect(Collectors.toList());

So after the filter you convert the objects to your other type and finally collect. Alternatively, you can use the mapping collector to transform your objects into another kind and then collect them like below

List<Output> outputList= inputList.stream()
        .filter(p ->  p.param1==10) 
        .collect(Collectors.mapping(j -> getOutput(j), Collectors.toList()));

Upvotes: 6

Related Questions