Sobes.tech
Middle

What are streams used for in the new version of Java?

sobes.tech AI

Answer from AI

Streams in Java 8+ are used for declarative processing of sequences of data. They allow performing functional operations on collections (lists, sets), arrays, or other data sources in a pipeline style.

Main advantages of using streams:

  • Declarative style: They allow describing "what" needs to be done with data, rather than "how". This makes the code more readable and understandable.
  • Lazy evaluation: Operations are processed only when necessary, which can improve performance, especially when working with large data volumes.
  • Parallel processing: Streams can be easily parallelized (using parallelStream()), enabling efficient utilization of multi-core processors.
  • Reduction of boilerplate code: They replace traditional loops and iterators with more expressive and concise constructs.
  • Immutability: Streams do not modify the original data source.

Examples of common stream operations:

  • Filtering: filter() - selecting elements based on a condition.
  • Mapping: map() - transforming each element.
  • Sorting: sorted() - sorting elements.
  • Distinct elements: distinct() - removing duplicates.
  • Grouping: collect(Collectors.groupingBy(...)) - grouping elements by a criterion.
  • Statistics/Aggregation: count(), sum(), average(), max(), min(), reduce() - performing aggregate operations.
  • Collecting into a collection: collect(Collectors.toList()), collect(Collectors.toSet()) - collecting results into a collection.

Example usage:

// Filtering and transforming a list of strings using streams
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

List<String> filteredNames = names.stream() // Create a stream from the list
                                   .filter(name -> name.startsWith("A")) // Filter: keep only names starting with "A"
                                   .map(String::toUpperCase) // Transform: convert each name to uppercase
                                   .collect(Collectors.toList()); // Collect the result into a new List

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