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?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • 2
    flatMap() is not terminal operation. You should call any terminal operation if you want to return result. – Hatice Feb 13 '19 at 14:24

2 Answers2

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
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

Naman
  • 27,789
  • 26
  • 218
  • 353
David Pérez Cabrera
  • 4,960
  • 2
  • 23
  • 37
  • 1
    You're right. Its called for each `Application` and that is where it is getting *operated upon.* and hence the error. `.stream` should be a better approach here. – Naman Feb 13 '19 at 15:05