Sitemap

Java — Streams and usage

What is a Java Stream?

--

  • A stream is a sequence of elements supporting sequential and parallel operations.
  • It doesn’t store data, but rather processes data from a source (like List, Set, or arrays).

Stream Pipeline Structure

A typical stream pipeline has 3 components:

  1. Source (e.g., list.stream())
  2. Intermediate Operations (e.g., filter, map)
  3. Terminal Operation (e.g., collect, forEach)
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());

Common Stream Functions (Internal APIs)

🔹 1. filter(Predicate)-Filters elements based on a boolean condition.

list.stream().filter(x -> x > 5)

🔹 2. map(Function)- Transforms each element.

names.stream().map(String::toUpperCase)

🔹 3. flatMap(Function)- Flattens nested structures.

listOfLists.stream().flatMap(List::stream)

🔹 4. distinct()- Removes duplicates.

list.stream().distinct()

🔹 5. sorted(), sorted(Comparator)- Sorts the stream.

list.stream().sorted()
list.stream().sorted(Comparator.reverseOrder())

🔹 6. limit(n) / skip(n)- Limit or skip elements in a stream.

list.stream().limit(5)
list.stream().skip(2)

🔹 7. peek(Consumer)- Useful for debugging — lets you “peek” at the elements without modifying.

list.stream()
.peek(System.out::println)
.filter(x -> x > 10)

🔹 8. collect(...) (Terminal)- Gather the result into a collection or a value.

list.stream().collect(Collectors.toList())
list.stream().collect(Collectors.joining(", "))
list.stream().collect(Collectors.groupingBy(String::length))

🔹 9. forEach(...) (Terminal)- Apply an action to each element (doesn’t return a result).

list.stream().forEach(System.out::println)

🔹 10. reduce(...) (Terminal)- Combine elements into a single result.

int sum = list.stream().reduce(0, Integer::sum);

🔹 11. anyMatch, allMatch, noneMatch- Match predicates against stream content.

list.stream().anyMatch(x -> x > 10)
list.stream().allMatch(x -> x != null)

🔹 12. findFirst, findAny- Retrieve elements from a stream.

list.stream().findFirst()
list.parallelStream().findAny()

🔹 13. parallelStream()- Run the stream in parallel for better performance (in some cases).

list.parallelStream()
List<Order> recentOrders = orders.stream()
.filter(o -> o.getDate().isAfter(LocalDate.now().minusDays(30)))
.filter(o -> o.getAmount() > 100)
.sorted(Comparator.comparing(Order::getDate).reversed())
.collect(Collectors.toList());

Real-World Use Case: Order Processing with Streams

Imagine we have a list of Order objects and we want to:

  • Filter orders from the last 7 days
  • Only include orders above $100
  • Sort by amount descending
  • Collect order IDs into a list
List<Order> recentLargeOrderIds = orders.stream()
.filter(o -> o.getDate().isAfter(LocalDate.now().minusDays(7)))
.filter(o -> o.getAmount() > 100)
.sorted(Comparator.comparing(Order::getAmount).reversed())
.map(Order::getId)
.collect(Collectors.toList());

map() vs flatMap()

map() Returns a Stream of Stream (or nested structure)

Get Naveen’s stories in your inbox

Join Medium for free to get updates from this writer.

flatMap() Returns a flattened Stream (no nesting)

class Category {
String name;
List<Product> products;
}

class Product {
String name;
}

// With map, You still need to unwrap the inner list manually if you want a flat list of all products
List<Category> categories = ...;

Stream<List<Product>> productLists = categories.stream()
.map(Category::getProducts);

// With flatmap, All products from all categories are flattened into a single stream.

Stream<Product> allProducts = categories.stream()
.flatMap(category -> category.getProducts().stream());

filter() vs map()

filter() Selects elements based on a condition. Reduces the number of elements

map() Transforms each element to another form. Keeps the number the same (usually)

list.stream().filter(n -> n > 10)   // keeps only values > 10
list.stream().map(n -> n * 2) // multiplies every value by 2

collect() vs forEach()

collect() Terminal operation, returns result. Used to gather results into a collection

forEach() Terminal operation, returns void . Used for side effects (like printing) Functional More imperative

List<String> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());

people.stream().forEach(System.out::println);

reduce() vs collect()

reduce() Reduces stream to a single value. Best for aggregation (sum, product)

collect() Accumulates elements into a collection. Best for building collections

int sum = numbers.stream().reduce(0, Integer::sum); // reduces to single int

List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList()); // collects to list

Best Practices

  • Avoid mutating state inside streams.
  • Prefer method references (map(String::toUpperCase)).
  • Use parallel streams cautiously — only for CPU-heavy, independent operations.
  • Use collect(Collectors.toMap()), groupingBy(), and partitioningBy() for powerful aggregations.

--

--