Sobes.tech
Middle

Why are streams used in the new version of Java?

sobes.tech AI

Answer from AI

The use of streams in newer versions of Java (starting from Java 8) is driven by several reasons related to efficiency, code readability, and data processing parallelism:

  • Functional programming: Streams allow writing code in a more declarative style, focusing on what needs to be done with data rather than how. This improves readability and maintainability.
  • Parallel processing: Streams make it easy to parallelize collection processing operations using parallelStream(). The JVM manages data splitting and result merging, simplifying the development of multithreaded applications.
  • Efficiency: Lazy evaluation in streams means operations are performed only when necessary, reducing overhead. Intermediate operations (map, filter) do not execute immediately until a terminal operation (collect, forEach) is invoked.
  • Enhanced collection processing: They provide a set of standard, high-level operations for filtering, mapping, and aggregating data in collections, reducing boilerplate code with loops.
  • Immutable operations: Streams do not modify the original collection from which they are created, supporting immutability principles and simplifying debugging.
// Example of using streams for filtering and mapping
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

List<String> filteredNames = names.stream() // Creating a stream
                                  .filter(name -> name.startsWith("C")) // Filtering
                                  .map(String::toUpperCase) // Mapping
                                  .collect(Collectors.toList()); // Collecting result into a new list

System.out.println(filteredNames); // Output: [CHARLIE]

Parallel streams:

// Example of parallel processing in a stream
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

int sum = numbers.parallelStream() // Creating a parallel stream
                   .mapToInt(Integer::intValue) // Converting to IntStream
                   .sum(); // Summing

System.out.println(sum); // Output: 55 (can be computed faster on multi-core systems)