Java Streams API is a modern way to work with collections of data. It helps you do operations like filtering, sorting, and mapping in a clean and easy way.
Streams were added in Java 8. They let you write short and clear code.
A stream is a sequence of data. It does not store data. It only processes data from a source like a list, array, or set.
Think of it like a water pipe. The data flows through the pipe, and you can change it along the way.
Imagine you have a basket of apples. You want to pick only red apples, clean them, and put them in a box.
This is similar to how a stream works:
import java.util.*; import java.util.stream.*; public class StreamExample { public static void main(String[] args) { Listnames = Arrays.asList("Alice", "Bob", "Charlie", "Anna"); List result = names.stream() .filter(name -> name.startsWith("A")) .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(result); // [ALICE, ANNA] } }
Streams only run when needed. If you write a stream but do not call a terminal operation, nothing happens.
Java can run streams in parallel using parallelStream()
. This makes them faster for big data.
Listnumbers = Arrays.asList(1, 2, 3, 4, 5); numbers.parallelStream().forEach(System.out::println);
Streams are powerful. They help you write clean and short code. You can filter, map, and collect data easily. Try them in your next Java project!