DEV Community

Nikko Ferwelo
Nikko Ferwelo

Posted on

πŸš€Java Stream API Cheat Sheet for Developers

Hey everyone! πŸ‘‹

I’ve put together a concise Java Stream API Cheat Sheet to help you quickly reference important concepts, methods, and patterns in your Java projects. Whether you're an experienced developer or just getting started, this guide should serve as a handy resource for working with streams in Java.

Let’s dive in!

πŸ”— Core Concepts

Java Stream API: A powerful tool introduced in Java 8 for processing sequences of elements in a functional style.

Functional Interfaces: Core to the Stream API, allowing the use of lambda expressions. Some key interfaces include:

  • Predicate: Represents a boolean-valued function.
  • Function: Represents a function that takes an input and returns a result.
  • Consumer: Represents an operation that takes an input and returns no result.
  • Supplier: Represents a supplier of results.

πŸ“¦ Creating Streams

Streams can be created from various sources:

  1. From Collections:
   List<String> list = Arrays.asList("a", "b", "c");
   Stream<String> stream = list.stream();
Enter fullscreen mode Exit fullscreen mode
  1. From Arrays:
   String[] array = {"a", "b", "c"};
   Stream<String> stream = Arrays.stream(array);
Enter fullscreen mode Exit fullscreen mode
  1. From Values:
   Stream<String> stream = Stream.of("a", "b", "c");
Enter fullscreen mode Exit fullscreen mode
  1. From Files:
   Stream<String> lines = Files.lines(Paths.get("file.txt"));
Enter fullscreen mode Exit fullscreen mode

πŸ”— Stream Operations

Stream operations are divided into intermediate and terminal operations:

Intermediate Operations (Lazy)

  • filter(): Filters elements based on a predicate.
  stream.filter(s -> s.startsWith("a"));
Enter fullscreen mode Exit fullscreen mode
  • map(): Transforms each element.
  stream.map(String::toUpperCase);
Enter fullscreen mode Exit fullscreen mode
  • flatMap(): Flattens nested streams.
  stream.flatMap(Collection::stream);
Enter fullscreen mode Exit fullscreen mode
  • sorted(): Sorts elements.
  stream.sorted();
Enter fullscreen mode Exit fullscreen mode
  • distinct(): Removes duplicates.
  stream.distinct();
Enter fullscreen mode Exit fullscreen mode

Terminal Operations (Eager)

  • collect(): Collects the results into a collection.
  List<String> result = stream.collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode
  • forEach(): Performs an action for each element.
  stream.forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode
  • reduce(): Reduces the elements to a single value.
  Optional<String> concatenated = stream.reduce(String::concat);
Enter fullscreen mode Exit fullscreen mode
  • count(): Counts the number of elements.
  long count = stream.count();
Enter fullscreen mode Exit fullscreen mode
  • findFirst(): Returns the first element.
  Optional<String> first = stream.findFirst();
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Common Patterns

  1. Filtering and Collecting:
   List<String> filteredList = list.stream()
                                   .filter(s -> s.length() > 2)
                                   .collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode
  1. Mapping and Reducing:
   int sum = list.stream()
                 .map(String::length)
                 .reduce(0, Integer::sum);
Enter fullscreen mode Exit fullscreen mode
  1. Grouping and Counting:
   Map<String, Long> grouping = list.stream()
                                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Enter fullscreen mode Exit fullscreen mode

πŸš€ Stream Characteristics

  • Parallel Streams: Split the stream into multiple threads for parallel processing.
  Stream<String> parallelStream = list.parallelStream();
Enter fullscreen mode Exit fullscreen mode
  • Infinite Streams: Generate streams with no fixed size.
  Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 1);
Enter fullscreen mode Exit fullscreen mode

πŸ“¦ Advanced Topics

  • Custom Collectors: Create your own collectors for complex reduction operations.
  • FlatMap for Nested Structures: Flatten complex data structures.
  • Stream Pipelines: Combine multiple stream operations for powerful data processing.

🧩 Example Use Cases

  • Data Filtering: Filter a list of objects based on multiple criteria.
  • Data Transformation: Convert a list of objects to a different type (e.g., DTOs).
  • Aggregation and Summary: Calculate statistics like sum, average, or max.

βš™οΈ Commands and Tools

  • JDK: Ensure you’re using Java 8 or higher to utilize the Stream API.
  • IDE: IntelliJ IDEA, Eclipse, or Visual Studio Code for Java development.

🧠 Best Practices

  • Prefer Immutability: Streams encourage a functional style, so avoid mutating shared state.
  • Reuse Streams Cautiously: Streams can only be consumed once; consider creating new streams for multiple operations.

I hope this Java Stream API Cheat Sheet helps you in your development journey! πŸš€ Feel free to bookmark it or share it with your fellow developers.

If you have any additions or suggestions, drop them in the comments below. Happy coding! πŸ’»

Connect with me:


Top comments (1)

Collapse
 
twistor profile image
Twistor

nicely done.