You're using @SuppressWarnings("resource") which presumably suppresses a warning about an unclosed resource. This isn't one of the warnings emitted by javac. Web searches seem to indicate that Eclipse issues warnings if an AutoCloseable is left unclosed.

This is a reasonable warning according to the Java 7 specification that introduced AutoCloseable:

A resource that must be closed when it is no longer needed.

However, the Java 8 specification for AutoCloseable was relaxed to remove the "must be closed" clause. It now says, in part,

An object that may hold resources ... until it is closed.

It is possible, and in fact common, for a base class to implement AutoCloseable even though not all of its subclasses or instances will hold releasable resources. For code that must operate in complete generality, or when it is known that the AutoCloseable instance requires resource release, it is recommended to use try-with-resources constructions. However, when using facilities such as Stream that support both I/O-based and non-I/O-based forms, try-with-resources blocks are in general unnecessary when using non-I/O-based forms.

This issue was discussed extensively within the Lambda expert group; this message summarizes the decision. Among other things it mentions changes to the AutoCloseable specification (cited above) and the BaseStream specification (cited by other answers). It also mentions the possible need to adjust the Eclipse code inspector for the changed semantics, presumably not to emit warnings unconditionally for AutoCloseable objects. Apparently this message didn't get to the Eclipse folks or they haven't changed it yet.

In summary, if Eclipse warnings are leading you into thinking that you need to close all AutoCloseable objects, that's incorrect. Only certain specific AutoCloseable objects need to be closed. Eclipse needs to be fixed (if it hasn't already) not to emit warnings for all AutoCloseable objects.

Answer from Stuart Marks on Stack Overflow
Top answer
1 of 4
39

You're using @SuppressWarnings("resource") which presumably suppresses a warning about an unclosed resource. This isn't one of the warnings emitted by javac. Web searches seem to indicate that Eclipse issues warnings if an AutoCloseable is left unclosed.

This is a reasonable warning according to the Java 7 specification that introduced AutoCloseable:

A resource that must be closed when it is no longer needed.

However, the Java 8 specification for AutoCloseable was relaxed to remove the "must be closed" clause. It now says, in part,

An object that may hold resources ... until it is closed.

It is possible, and in fact common, for a base class to implement AutoCloseable even though not all of its subclasses or instances will hold releasable resources. For code that must operate in complete generality, or when it is known that the AutoCloseable instance requires resource release, it is recommended to use try-with-resources constructions. However, when using facilities such as Stream that support both I/O-based and non-I/O-based forms, try-with-resources blocks are in general unnecessary when using non-I/O-based forms.

This issue was discussed extensively within the Lambda expert group; this message summarizes the decision. Among other things it mentions changes to the AutoCloseable specification (cited above) and the BaseStream specification (cited by other answers). It also mentions the possible need to adjust the Eclipse code inspector for the changed semantics, presumably not to emit warnings unconditionally for AutoCloseable objects. Apparently this message didn't get to the Eclipse folks or they haven't changed it yet.

In summary, if Eclipse warnings are leading you into thinking that you need to close all AutoCloseable objects, that's incorrect. Only certain specific AutoCloseable objects need to be closed. Eclipse needs to be fixed (if it hasn't already) not to emit warnings for all AutoCloseable objects.

2 of 4
17

You only need to close Streams if the stream needs to do any cleanup of itself, usually I/O. Your example uses an HashSet so it doesn't need to be closed.

from the Stream javadoc:

Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management.

So in your example this should work without issue

List<ImageView> collect = photos.stream()
                       .map(photo -> ...)
                       .collect(toList());

EDIT

Even if you need to clean up resources, you should be able to use just one try-with-resource. Let's pretend you are reading a file where each line in the file is a path to an image:

 try(Stream<String> lines = Files.lines(file)){
       List<ImageView> collect = lines
                                  .map(line -> new ImageView( ImageIO.read(new File(line)))
                                  .collect(toList());
  }
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
How to use a stream in Java 8 - Examples Java Code Geeks - 2026
May 7, 2020 - Download You can download the full source code of this example here: Java Stream – How to use Java 8 streams
🌐
Pluralsight
pluralsight.com › tech insights & how-to guides › tech guides & tutorials
Java 8 Stream API: Part 1 | Pluralsight
Anonymous classes are compiled into inner classes, while lambda expressions are converted into private, static (in some cases) methods within their enclosing class. Using the invokedynamic instruction (added in Java 7), they are bound dynamically. Simply put, since there's no need to load another class, lambda expressions are more efficient than anonymous classes. With this in mind, let's introduce the Stream interface.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-stream-collect-method-examples
Java Stream collect() Method Examples | DigitalOcean
August 3, 2022 - While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial. ... 3. Stream collect() to Map List numbers = List.of(1, ...
🌐
Stackify
stackify.com › streams-guide-java-8
A Guide to Java Streams: In-Depth Tutorial With Examples
September 4, 2024 - The takeWhile method is a significant addition to the Streams API in Java 9. It allows you to consume elements from a stream as long as a specified condition holds. Once the condition becomes false, the method stops and returns a new stream containing only the elements that match the predicate. View this as a conditional filter with a short-circuiting capability. Here’s a simple example to illustrate:
🌐
Reddit
reddit.com › r/learnprogramming › any good tutorials on streams in java 8?
r/learnprogramming on Reddit: Any good tutorials on Streams in Java 8?
February 17, 2020 -

When I studied Java, it was before they introduced Streams. Now I'm seeing them used as one-line solutions in basically every programming puzzle I find. I've read the main documentation, but it still feels like a stranger to me compared to other Java objects like Collections, Maps, Lists, etc. I'm worried that if this remains the case, my career will worsen; at best, I'd like to understand it well for my own sake to better master Java.

Does r/learnprogramming have any good resources, video tutorials or courses that could help me get comfortable with streams?

Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java streams › the java stream api tutorial
The Java Stream API Tutorial | Baeldung
October 5, 2023 - Since Java 8, the Random class provides a wide range of methods for generating streams of primitives. For example, the following code creates a DoubleStream, which has three elements:
🌐
Coderanch
coderanch.com › t › 734576 › java › understand-stream
How can I understand what actually a stream is? (Features new in Java 8 forum at Coderanch)
- a function of the position in the stream. For example, a random number generator. Generally, however, the generator is not a seen as a function. Instead, it memorizes its state, so it does not actually take the position as an argument. - a function of the previous element.
🌐
Oracle
oracle.com › java › technical details
Processing Data with Java SE 8 Streams, Part 1
However, notice the use of lambda expressions (for example, t-> t.getCategory() == Transaction.GROCERY) and method references (for example, Transaction::getId), which you should be familiar with by now. (To brush up on lambda expressions, refer to previous Java Magazine articles and other resources listed at the end of this article.) For now, you can see a stream as an abstraction for expressing efficient, SQL-like operations on a collection of data.
🌐
Snap! Forum
forum.snap.berkeley.edu › share your projects
Lazy list evaluation, similar to Java Streams - Share your Projects - Snap! Forum
January 6, 2019 - Hello. ~2 years ago I tried Snap and I was clueless about many things - namely ringify. Now that I have discovered the beauty of lambda expressions, everything makes a lot more sense. 🙂 Anyways, because my college semester is over and I have nothing better to do, I have been experimenting with Snap and created this.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-8-stream-tutorial
Java 8 Stream Tutorial - GeeksforGeeks
Streams are widely used in real-world applications for processing collections of data in a cleaner and faster way. Below are some practical examples: ... Code Implementation: Here we implement a real-world example of filtering, sorting, mapping and collecting transactions using Java Streams.
Published   5 days ago
🌐
GitHub
gist.github.com › tahniat-ashraf › a03c2545adf0c5fbc339568b2a756846
Java Stream Api Examples · GitHub
A stream can hold complex data structures like Stream<List>. In cases like this, flatMap() helps us to flatten the data structure to simplify further operations.
🌐
DEV Community
dev.to › therealdumbprogrammer › all-about-java-streams-a-quick-hands-on-introduction-1hgj
All about Java Streams — a quick hands-on introduction - DEV Community
March 14, 2023 - // 3. From Collection System.out.println("From collections---------------"); List<String> languages = List.of("Java", "Python"); languages.stream().forEach(System.out::println); //by calling stream() IO API has been enhanced to return streams. Here’s an example, where we’re reading a file using Stream.
🌐
Capital One
capitalone.com › tech › software-engineering › java-streams-explained-simple-example
How to Use Java Streams Explained | Capital One
November 16, 2020 - .collect() : Collect the items in your stream into a certain collection: Building off of the previous example, collect() is another very important terminal operation in Java streams. Based on the collector you specify, the items in your streams will be collected into that collection.
🌐
How to do in Java
howtodoinjava.com › home › java streams › java stream api: real-world examples for beginners
Java Stream API: Real-world Examples for Beginners
September 19, 2023 - Streams are created on a source, e.g. a java.util.Collection like List or Set. The Map is not supported directly, we can create a stream of map keys, values or entries. Stream operations can either be executed sequentially or in parallel. when performed parallelly, it is called a parallel stream. Based on the above points, we can say that a Stream is: ... The given below ways are the most popular different ways to build streams from collections. In the given example, we are creating a stream of a fixed number of integers.
🌐
Medium
medium.com › javarevisited › java-8-stream-api-with-examples-fc7b083e9ebb
Java 8 Stream API with Examples. Introduced in Java 8, the Stream API is… | by Thameem Ansari | Javarevisited | Medium
March 8, 2022 - Java 8 Stream API with Examples Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined …
🌐
JetBrains
blog.jetbrains.com › idea › 2024 › 05 › easy-hacks-how-to-use-java-streams-for-working-with-data
Easy Hacks: How to Use Java Streams for Working With Data | The IntelliJ IDEA Blog
May 15, 2024 - The Optional type allows Java to execute your declarative stream statements, knowing it can give you a result, even though there could be no result at all, which brings us to the lesson of this section. In imperatively written code, we use if statements to be defensive and avoid app-breaking exceptions.
Top answer
1 of 6
56

The JDK's standard implementation of Stream is the internal class java.util.stream.ReferencePipeline, you cannot instantiate it directly.

Instead you can use java.util.stream.Stream.builder(), java.util.stream.StreamSupport.stream(Spliterator<T>, boolean) and various1, 2 other static factory methods to create an instance of the default implementation.

Using a spliterator is probably the most powerful approach as it allows you to provide objects lazily while also enabling efficient parallelization if your source can be divided into multiple chunks.

Additionally you can also convert streams back into spliterators, wrap them in a custom spliterator and then convert them back into a stream if you need to implement your own stateful intermediate operations - e.g. due to shortcomings in the standard APIs - since most available intermediate ops are not allowed to be stateful.
See this SO answer for an example.

In principle you could write your own implementation of the stream interface, but that would be quite tedious.

2 of 6
24

If you're wanting to make your own Stream because you want custom close() logic, the simplest solution is to create a Stream from an Iterator, and call onClose(Runnable). For instance, to stream from a Reader via Jackson:

MappingIterator<?> values = objectMapper.reader(type).readValues(reader);
return StreamSupport
        .stream(Spliterators.spliteratorUnknownSize(values, Spliterator.ORDERED), false)
        .onClose(() -> {
            try {
                reader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
🌐
Medium
medium.com › @anil.goyal0057 › mastering-java-streams-25-hands-on-examples-45d56ba52cf2
Mastering Java Streams: 25+ Hands-On Examples | by Anil Goyal | Medium
September 1, 2025 - ... Intermediate Operations: Return a new stream (e.g., map, filter, sorted). Terminal Operations: Produce a result (e.g., collect, reduce, forEach) ... Below are various examples with inline documentation to explain their functionality. package org.example.javastreams; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class StreamInterviewProgramming { public static void main(String[] args) { // Question 1: Given a list of integers, find the k most frequent elements.
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-in-java
Stream In Java - GeeksforGeeks
Examples · Quizzes · Projects · Cheatsheet · DSA in Java · Java Collection · Last Updated : 18 Mar, 2026 · Stream was introduced in Java 8, the Stream API is used to process collections of objects. It is a sequence of objects that supports various methods that can be pipelined to produce the desired result.
Published   4 weeks ago