Java8 - Creating streams from different data sources

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:36:24 Viewed : 270


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:

1. From Collections:

You can create a stream from a collection using the stream() method:

java
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1"); Stream<String> streamFromList = myList.stream();

2. From Arrays:

Arrays support the stream() method as well:

java
String[] myArray = {"a1", "a2", "b1", "c2", "c1"}; Stream<String> streamFromArray = Arrays.stream(myArray);

3. From I/O Channels (Lines from a File):

You can create a stream of lines from a file using the Files.lines() method:

java
import 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(); }

4. From a String:

You can create a stream of characters from a string:

java
String myString = "Hello, World!"; IntStream streamFromChars = myString.chars();

5. From Generators:

You can create a stream using the Stream.generate() method or the Stream.iterate() method:

Using Stream.generate():

java
Stream<Integer> infiniteStream = Stream.generate(() -> 1);

Using Stream.iterate():

java
Stream<Integer> streamFromIterate = Stream.iterate(0, n -> n + 2).limit(5);

6. From a Range of Values:

You can create a stream of values within a specified range:

java
IntStream streamFromRange = IntStream.range(1, 6); // 1, 2, 3, 4, 5

7. From a Map:

You can create streams from the keys, values, or entries of a map:

java
Map<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.

Search
Related Articles

Leave a Comment: