A2oz

What are the different stream classes in Java?

Published in Java Programming 2 mins read

Java provides different stream classes to facilitate working with sequences of elements. These classes are categorized into two main types:

1. Base Stream Classes

  • Stream: The fundamental interface that defines the core operations for working with streams. It provides methods for filtering, mapping, reducing, and collecting elements.
  • IntStream: A specialized stream for working with sequences of int values. It provides methods for working with primitive integers.
  • LongStream: Similar to IntStream, this stream handles sequences of long values.
  • DoubleStream: A stream designed for working with sequences of double values.

2. Stream Builders

  • Stream.Builder: Used to create streams from a collection of elements. It allows you to add elements one by one.
  • IntStream.Builder: Specifically used to build streams of int values.
  • LongStream.Builder: Used to build streams of long values.
  • DoubleStream.Builder: Used to build streams of double values.

Example:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamClassesExample {

    public static void main(String[] args) {

        // Creating a stream from a list
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        Stream<Integer> stream = numbers.stream();

        // Using IntStream to calculate the sum of squares
        int sumOfSquares = IntStream.of(1, 2, 3, 4, 5)
                .map(n -> n * n)
                .sum();

        // Building a stream using Stream.Builder
        Stream<String> names = Stream.<String>builder()
                .add("Alice")
                .add("Bob")
                .add("Charlie")
                .build();

        // Collecting elements from a stream
        List<String> collectedNames = names.collect(Collectors.toList());

    }
}

These classes provide a powerful and flexible way to process data in Java, enabling efficient and concise code.

Related Articles