Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:36:24 Viewed : 217
In Java, streams can be created from various data sources, including collections, arrays, I/O channels, and generators. Here are some common ways to create streams from different data sources:
You can create a stream from a collection using the stream()
method:
javaList<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
Stream<String> streamFromList = myList.stream();
Arrays support the stream()
method as well:
javaString[] myArray = {"a1", "a2", "b1", "c2", "c1"};
Stream<String> streamFromArray = Arrays.stream(myArray);
You can create a stream of lines from a file using the Files.lines()
method:
javaimport java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.stream.Stream;
try {
Stream<String> streamFromLines = Files.lines(Paths.get("path/to/file.txt"));
} catch (IOException e) {
e.printStackTrace();
}
You can create a stream of characters from a string:
javaString myString = "Hello, World!";
IntStream streamFromChars = myString.chars();
You can create a stream using the Stream.generate()
method or the Stream.iterate()
method:
Stream.generate()
:javaStream<Integer> infiniteStream = Stream.generate(() -> 1);
Stream.iterate()
:javaStream<Integer> streamFromIterate = Stream.iterate(0, n -> n + 2).limit(5);
You can create a stream of values within a specified range:
javaIntStream streamFromRange = IntStream.range(1, 6); // 1, 2, 3, 4, 5
You can create streams from the keys, values, or entries of a map:
javaMap<String, Integer> myMap = Map.of("a", 1, "b", 2, "c", 3);
// Stream of keys
Stream<String> keysStream = myMap.keySet().stream();
// Stream of values
Stream<Integer> valuesStream = myMap.values().stream();
// Stream of entries
Stream<Map.Entry<String, Integer>> entriesStream = myMap.entrySet().stream();
These examples cover various scenarios where you might want to create streams from different data sources. The flexibility of the Stream API in Java makes it easy to work with diverse data structures and sources in a functional and expressive manner.