Sobes.tech
Middle

Milleks kasutatakse voogusid Java uues versioonis?

sobes.tech AI

Vastus AI-lt

Streams in Java 8+ are used for declarative processing of data sequences. 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, not "how". This makes the code more readable and understandable.
  • Lazy computations: Operations are executed only when necessary, which can improve performance, especially when working with large data volumes.
  • Parallel processing: Streams can be easily parallelized (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 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 results into a collection: collect(Collectors.toList()), collect(Collectors.toSet()) - collecting results.

Example of 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]