Skip to content
Advertisement

Java streams: flatMap returns Stream of Objects

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement