0

I have a lambda expression where I want to create a list of object but I am getting the error

List<ClassObject> classObject = obj1.getFileId().stream()
                .map(x -> obj1.getCustomObj().stream()
                        .map(y -> obj1.builder().Id(x).name(y.getName()).value(y.getValue())
                                .details(obj1.getDetails()).build()))
                .collect(Collectors.toList());

Error

Type mismatch: cannot convert from List<Stream<ClassObject>> to List<ClassObject>

I want List<ClassObject> as return type from the lambda expression. How can I achieve that?

ruhewo
  • 97
  • 1
  • 10
  • Possible duplicate of https://stackoverflow.com/questions/14830313/retrieving-a-list-from-a-java-util-stream-stream-in-java-8 ? – onnoweb Jun 05 '19 at 17:32
  • 1
    Nope, that is not a good duplicate. The answer is flatmap() not map. – GhostCat Jun 05 '19 at 17:34

1 Answers1

4

Use flatMap:

List<ClassObject> classObject = obj1.getFileId().stream()
            .flatMap(x -> obj1.getCustomObj().stream()
                    .map(y -> obj1.builder().Id(x).name(y.getName()).value(y.getValue())
                            .details(obj1.getDetails()).build()))
            .collect(Collectors.toList());
Gareth Davis
  • 27,701
  • 12
  • 73
  • 106