Sobes.tech
Junior

What are streams used for in Java?

sobes.tech AI

Answer from AI

For declarative data collection processing. They allow performing sequential or parallel operations on collection elements, such as filtering, mapping (transformation), aggregation, and collecting results, making the code more readable and flexible.

Main advantages:

  • Declarativeness: Instead of describing "how" to perform an operation (loops, iterators), we describe "what" needs to be done with the data.
  • Parallelism: Easily switch between sequential and parallel processing, which is useful for multi-core systems.
  • Laziness: Intermediate operations are executed only as needed when a terminal operation is present.
  • Conciseness: Often allows reducing the amount of code compared to traditional loops.

Example of sequential processing:

// Getting a list of user names over 18 years old and converting to uppercase
List<User> users = ... // Your collection of users
List<String> adultUserNames = users.stream()
    .filter(user -> user.getAge() >= 18) // Filtering users by age
    .map(user -> user.getName().toUpperCase()) // Converting name to uppercase
    .collect(Collectors.toList()); // Collecting results into a List

Example of parallel processing:

// Parallel summation of large numbers in a list
List<Long> numbers = ... // Your collection of numbers
long sum = numbers.parallelStream()
    .reduce(0L, Long::sum); // Parallel summation

Thus, streams in Java are used for a functional and efficient approach to data processing.

What are streams used for in Java? — Java - sobes.tech