Sobes.tech
Middle

Miks kasutatakse Java uues versioonis voogusid?

sobes.tech AI

Vastus AI-lt

In newer versions of Java (starting from Java 8), the use of streams is motivated by several reasons related to efficiency, code readability, and parallel data processing:

  • 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 loop code.
  • Immutable operations: Streams do not modify the original collection from which they are created, supporting immutability principles and easing 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 streams
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)