I'm trying to reproduce the following behavior with the help of streams:
public List<ObjDTO> getList(param1){
List<SomeObj> allObjs = getAll(param1);
List<ObjDTO> finalList = new ArrayList<>();
for (SomeObj someObj : allObjs){
SomeEnum someEnum = methodcall(someObj, param1);
if(!SomeEnum.VALUE.equals(someEnum)){
finalList.add(new ObjDTO(someObj, someEnum.getMessage()));
}
}
return finalList;
}
What i have so far:
public List<ObjDTO> getList(param1){
List<SomeObj> allObjs = getAll(param1);
return allObjs.stream()
.filter(someObj -> !SomeEnum.VALUE.equals(methodcall(someObj, param1)))
.map(someObj -> new ObjDTO(someObj, someEnum.getMessage()))
.collect(Collectors.toList());
}
The problem here is that I don't have that someEnum
anymore so I need to somehow create a variable in filter()
and use it inside map()
.
Is there a way to do this or does anyone find a better approach?
You can do it with a flatMap
:
return allObjs.stream()
.flatMap(someObj ->
Stream.of(methodcall(someObj, param1))
.filter(someEnum -> !SomeEnum.VALUE.equals(someEnum))
.map(someEnum -> Stream.of(new ObjDTO(someObj, someEnum.getMessage()))))
.collect(toList());