1

I've this code:

List<Application> applications = this.applicationDao.findAll();
Collection<Pair<Application, FileObject>> files = applications.stream()
    .flatMap(app -> streamOfFiles.map(file -> Pair.of(app, file)));

where streamOfFiles is an Stream<FileObject>

Currently, I'm getting this compilation message:

Type mismatch: cannot convert from Stream<Object> to Collection<Pair<Application,FileObject>>

Any ideas?

1
  • 2
    flatMap() is not terminal operation. You should call any terminal operation if you want to return result. Commented Feb 13, 2019 at 14:24

2 Answers 2

6

You seem to be missing the collect there :

Collection<Pair<Application, FileObject>> files = applications.stream()
        .flatMap(app -> files.stream().map(file -> Pair.of(app, file)))
        .collect(Collectors.toList()); // any collection you want

Edit: Since, streamOfFiles is getting consumed at a single flatMap operation, you should prefer to use a <collection>.stream() instead there to create the stream afresh for each app.

Sign up to request clarification or add additional context in comments.

Comments

3

You can't reuse streamOfFiles Stream while iterating over applications!

You need to transform streamOfFiles from a Stream<FileObject> to List<FileObject> and then:

List<FileObject> listOfFiles = streamOfFiles.collect(Collectors.toList());
List<Application> applications = this.applicationDao.findAll();
Collection<Pair<Application, FileObject>> files =  applications.stream()
            .flatMap(app -> listOfFiles.stream().map(file -> Pair.of(app, file)))
            .collect(Collectors.toList());

A simple example to prove that:

Stream<Integer> s = IntStream.range(0, 100).boxed();
IntStream.range(0, 100).boxed()
         .flatMap(i -> s.map(j -> i * j))
         .collect(Collectors.toList());

It throws this Exception:

java.lang.IllegalStateException: stream has already been operated upon or closed

1 Comment

You're right. Its called for each Application and that is where it is getting operated upon. and hence the error. <collection>.stream should be a better approach here.

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.