Stream and IntStream in java 8 are used to process data in a simple and efficient way. Stream works with object types, while IntStream is a special stream for primitive int values. In this article, you will learn how to use Stream and IntStream in Java 8 with syntax, examples, and output.
Stream in Java 8 :-
• Stream<T> is used for processing a sequence of object values.
• It supports operations such as filter, map, sorted, and collect
• Stream.of() is a static method used to create a sequential Stream containing specified object elements.
• It is part of the java.util.stream.Stream interface.
• Stream<String> is a stream of String objects.
Example: Stream<String>
Syntax : Stream<T> stream
IntStream in Java 8 :-
• IntStream is a primitive specialization of the Stream interface.
• It is used to work with int values directly, which improves performance by avoiding boxing and unboxing.
• This class is a part of java.util.stream package.
• IntStream.of() is a static method used to create an IntStream containing specified int values.
Example: IntStream.of(1, 2, 3)
Syntax : static IntStream of(int… values)
Code Explanation (Step-by-Step) :-
- Stream.of(“well”, “hello”, “right”) creates a stream of string values.
- collect(Collectors.toList()) converts the stream into a list.
- From forEach() prints each string element.
- IntStream.of(1, 2, 3, 4, 5, 6) creates a stream of primitive integers.
- boxed() converts primitive int values into Integer objects.
- collect(Collectors.toList()) stores those values in a list.
- forEach(System.out::println) prints each integer value.
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
System.out.println("Using Stream.of() to create a stream and print the values:");
Stream stream = Stream.of("well", "hello", "right");
List list = stream.collect(Collectors.toList());
list.forEach(value -> System.out.println(value));
System.out.println("\nUsing IntStream.of() to create a stream of int values and print them:");
IntStream iStream = IntStream.of(1, 2, 3, 4, 5, 6);
List iList = iStream.boxed().collect(Collectors.toList());
iList.forEach(System.out::println);
}
}
Output :-
Using Stream.of() to create a stream and print the values:
well
hello
right
Using IntStream.of() to create a stream of int values and print them:
1
2
3
4
5
6
Difference Between Stream.of() and IntStream.of()
- Stream.of() works with object types like String, Integer, and Employee.
- IntStream.of() works with primitive int values directly.