Sobes.tech
Junior — Middle

Can you explain the concept of Stream API in Java and how it is used for data processing?

sobes.tech AI

Answer from AI

Stream API in Java is a powerful tool for processing collections of data in a functional style. It allows performing operations on sequences of elements, such as filtering, transforming, sorting, and aggregating, using method call chains.

Main features:

  • Lazy processing — operations are performed only when necessary.
  • Parallelism — easy to switch to parallel processing.
  • Code readability — code becomes more concise and understandable.

Example of using Stream API for filtering and transforming a list of strings:

import java.util.*;
import java.util.stream.*;

public class StreamExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");

        List<String> filtered = names.stream()
            .filter(name -> name.length() > 3)  // filtering by length
            .map(String::toUpperCase)           // transforming to uppercase
            .collect(Collectors.toList());     // collecting the result into a list

        System.out.println(filtered); // [ANNA, CHARLIE, DAVID]
    }
}

Thus, Stream API simplifies and accelerates data processing, making the code more expressive.

Can you explain the concept of Stream API in Java and… - sobes.tech