Stream creation in java

Stream creation in java

In the Java programming language, the Java Stream API was introduced in Java 8. A stream is a user-defined, continuous sequence or group of data type element values ​​in a Java program. It allows Java developers to perform data operations such as filtering, mapping, sorting, arranging, and minimizing Java data collections in a declarative order.

Stream creation in java

Important about the Stream API – Remember, Java streams are not a data structure format and do not store data. The Stream API processes data from sources such as collections, arrays, or generated data sequences as needed.

Creating a stream from a collection in Java.

In a Java program, the easiest way to create a stream data type is to call the stream() function method on the collection data type.

import java.util.*;

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

List<String> cars = Arrays.asList(

“Tata Punch”, “Hyundai Creta”, “Mahindra Thar”, “Toyota Innova Hycross” , “Volkswagen Golf”

);

Stream<String> stream = cars.stream();

stream.forEach(System.out::println);

}

}

Here is the stream flow in this program.

List data type method

↓

stream() function method

↓

Stream<String>

↓

intermediate operation

↓

terminal operation

Example of stream method.

cars.stream()

.filter(cars -> cars.length() > 5)

.forEach(System.out::println);

Creating a stream from a Set data type in Java.

In a Java program, you can create a stream data type element from a Set data type using the stream() function method.

import java.util.*;

public class Main {

public static void main(String[] args) {

Set<Integer> values ​​= new HashSet<>();

values.add(12);

values.add(19);

values.add(29);

values.add(89);

values.add(17);

values.add(99);

values.stream()

.forEach(System.out::println);

}

}

In this example, a Set data type does not generally guarantee the insertion order of new data elements, so the output order may depend on a specific Set implementation.

Creating Stream data from a Map in Java.

A Map data type in Java programs does not have a direct stream() function method.

Instead, Java users can create streams from it.

  • keySet() function
  • values() function
  • entrySet() function

A stream of keys in a Java program.

import java.util.*;

import java.util.stream.*;

public class Main {

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(1, “Hero Splendor Plus”);

map.put(2, “TVS Raider 125”);

map.put(3, “Bajaj Pulsar N160”);

map.put(4, “Yamaha MT-15 Version 2.0”);

map.put(5, “Royal Enfield Classic 350”);

// 1. Stream of map data keys

System.out.println(“Stream of map data type keys:”);

map.keySet()

.stream()

.forEach(System.out::println);

// 2. Stream of map data values

System.out.println(“\nStream of map data type values:”);

map.values()

.stream()

.forEach(System.out::println);

// 3. Number of Stream map data type of entries

System.out.println(“\nStream of map data type entries:”);

map.entrySet()

.stream()

.forEach(entry ->

System.out.println(

entry.getKey() + ” – ” + entry.getValue()

)

);

}

}

Creating Stream Data Type from Array in Java.

The Java programming language provides its users with the Arrays.stream() function method to create a stream method from an array data type.

Object Array Data Type Methods in Java.

import java.util.Arrays;

import java.util.stream.Stream;

import java.util.stream.IntStream;

import java.util.stream.LongStream;

import java.util.stream.DoubleStream;

public class Main {

public static void main(String[] args) {

// String of array data type

String[] course = {“Nielit O Level”, “Nielit A Level”, “Nielit B Level”, “Nielit C Level”};

System.out.println(“String of array data type stream method:”);

Stream<String> courseStream = Arrays.stream(course);

courseStream.forEach(System.out::println);

//Integer array primitive data type method

int[] integer = {23, 77, 98, 33, 44, 100};

System.out.println(“\nIntStream data type method:”);

IntStream intStream = Arrays.stream(integer);

intStream.forEach(System.out::println);

// Long integer primitive array data type method

long[] longinteger = {22L, 44L, 72L, 80L, 99L };

System.out.println(“\nLongStream data type method:”);

LongStream longStream = Arrays.stream(longinteger);

longStream.forEach(System.out::println);

// Double primitive data type array method

double[] decimalinteger = {8.7, 17.1, 33.3, 44.9, 89.2 };

System.out.println(“\nDoubleStream data type method:”);

DoubleStream doubleStream = Arrays.stream(decimalinteger);

doubleStream.forEach(System.out::println);

}

}

Creating a stream in Java using the Stream.of() function method.

The Stream.of() function method in the Java programming language is used when the Java user already has some values ​​defined.

Stream<String> stream =

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

Stream<String> stream = Stream.of(“Desktop”, “Laptop”, “Notebook” , “Palmtop”);

stream.forEach(System.out::println);

}

}

Java users can also use the Stream.of() method with integer data types.

Stream<Integer> stream =

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

Stream<Integer> stream = Stream.of(22, 33, 55, 69, 77, 99);

stream.forEach(System.out::println);

}

}

Stream.of() function method with Array data data type.

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

String[] programmig = {“Rust”, “Matlab”, “Pearl”, “Swift C”};

Stream<String> stream = Stream.of(programmig);

stream.forEach(System.out::println);

}

}

This example creates a stream data value containing the elements of an array.

Creating an empty stream in Java.

Java provides the Stream.empty() function method to create a stream data type without any data elements.

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

Stream<String> stream = Stream.empty();

System.out.println(stream.count());

}

}

It’s output.

0

In a Java program, the Stream.empty() function method is used when a method needs to return a stream, but no data type is defined for the return.

Example of the Stream.of method.

import java.util.stream.Stream;

public class Main {

public static Stream<String> getCountry(boolean available) {

if (available) {

return Stream.of(“India”, “Usa”, “Uk”, “China”, “Australia”);

}

return Stream.empty();

}

public static void main(String[] args) {

System.out.println(“List of country:”);

getCountry(true).forEach(System.out::println);

System.out.println(“Unlisted country:”);

getCountry(false).forEach(System.out::println);

}

}

Creating a stream using the Stream.generate() function method in Java.

In a Java program, the Stream.generate() function method creates a stream using a supplier method.

Stream<Integer> stream =

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

Stream<Integer> stream = Stream.generate(() -> 7);

stream.limit(7)

.forEach(System.out::println);

}

}

Why is the limit() function necessary in Stream.generate()?

In the current program, the Stream.generate() function creates an infinite stream.

According to the method above.

7 → 7 → 7 → 7 → 7 → 7 → 7 →…

For this reason, Java users commonly use the limit() function method.

Another example of the Stream.generate() function.

Stream<Double> randomNumbers =

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

Stream<Double> randomNumbers = Stream.generate(Math::random);

randomNumbers

.limit(8)

.forEach(System.out::println);

}

}

Creating a stream using the Stream.iterate() function method in Java.

The Stream.iterate() function method in Java creates a stream by repeatedly applying a function.

Syntax of the Stream.iterate() function method.

Stream.iterate(seed, function)

Example of the Stream.iterate() function method.

Stream<Integer> numbers =

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

Stream<Integer> numbers = Stream.iterate(1, num -> num + 1);

numbers.limit(7)

.forEach(System.out::println);

}

}

It’s output.

In this example.

1

is the starting value.

After that,

num -> num + 1

creates the next value.

Conceptually, it works like this:

1 → 2 → 3 → 4 → 5 → 6 → 7 → …

After that, this form creates an infinite stream, which is why the limit() function method is commonly used.

The iterate() function method with a Predicate in Java 9.

The Java 9 language version introduced another version of the iterate() function method.

Stream.iterate(seed, predicate, function)

Example of the iterate() function method.

Stream<Integer> numbers =

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

Stream.iterate(

1,

num -> num <= 9,

num -> num + 1

).forEach(System.out::println);

}

}

numbers.forEach(System.out::println);

Its output.

In this.

1

is its starting value.

num -> num <= 9

Here is the user-defined condition.

num -> num + 1

The next value is then created.

This feature in Java is used when developers want a stream to stop based on a condition.

Creating a primitive stream data type in Java with IntStream.

The Java programming language provides a stream function method for primitive data type methods.

  • IntStream
  • LongStream
  • DoubleStream

Example of a primitive stream data type.

IntStream stream =

import java.util.stream.IntStream;

public class Main {

public static void main(String[] args) {

IntStream stream = IntStream.of(24, 34, 38, 41, 55, 66);

stream.forEach(System.out::println);

}

}

Creating a stream using the IntStream.range() function method in Java.

The IntStream.range() function method in Java creates an integer value between a starting value and an ending value.

import java.util.stream.IntStream;

public class Main {

public static void main(String[] args) {

IntStream.range(1, 9)

.forEach(System.out::println);

}

}

Note that in the above program, the value 9 has been removed. Because of this,

IntStream.range(1, 9)

means:

1, 2, 3, 4, 5, 6, 7, 8

IntStream.rangeClosed() function method in Java.

The rangeClosed() function method in Java includes the ending value.

import java.util.stream.IntStream;

public class Main {

public static void main(String[] args) {

IntStream.rangeClosed(1, 9)

.forEach(System.out::println);

}

}

The difference between main and array is this.

range(1, 9)

→ 1 2 3 4 5 6 7 8

rangeClosed(1, 5)

→ 1 2 3 4 5 6 7 8 9

Creating a Stream from a String in Java.

In a Java program, a string can be converted to a stream of characters using the chars() function method.

public class Main {

public static void main(String[] args) {

String Comp_name = “Vcanhelpsu”;

Comp_name.chars()

.forEach(c -> System.out.println((char) c));

}

}

In this example, the chars() function creates an IntStream data, which is then converted to char text to print the text character value.

Creating a stream from a Java file.

In a Java program, the Files.lines() function method can create a stream, where each file element represents a line in the file.

import java.nio.file.*;

import java.io.IOException;

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) throws IOException {

try (Stream<String> lines = Files.lines(Paths.get(“sample.txt”))) {

lines.forEach(System.out::println);

}

}

}

In this example, this is especially useful when processing large text files, as it doesn’t require loading the entire file into memory at once. The try-with-resources statement is generally preferred.

try (Stream<String> lines =

{ try (Stream<String> lines = Files.lines(Paths.get(“sample.txt”))) {

lines.forEach(System.out::println); }

Creating a parallel stream in Java.

In a Java program, you can create a parallel stream using the collection parallelStream() function method.

List<Integer> numbers =

import java.util.Arrays;

import java.util.List;

public class Main {

public static void main(String[] args) {

List<Integer> values ​​= Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

values.parallelStream()

.forEach(System.out::println);

}

}

Here, in this example, a parallel stream is created. It can process data elements using multiple threads.

The main difference is.

numbers.stream();

This creates a sequential stream.

values.parallelStream();

This creates a parallel stream.

Parallel streams should not be automatically considered faster in a Java program. Their use depends entirely on the workload, data size, and the operation being performed.

Creating a stream and processing it simultaneously in Java.

This is a very basic Java stream pattern in a Java program.

List<Integer> numbers =

Arrays.asList(9, 21, 33, 44, 89, 100);

import java.util.Arrays;

import java.util.List;

public class Main {

public static void main(String[] args) {

List<Integer> integers =

Arrays.asList(9, 21, 33, 44, 89, 100); 44, 89, 100);

List<Integer> output =

integers.stream()

.filter(num -> num > 40)

.map(num -> num / 2 )

.toList();

System.out.println(output);

}

}

The processing pipeline in Java streams is something like this.

Collection data type

↓

stream() function method

↓

filter() data function

↓

map() data function

↓

toList() data function

↓

Output

Essential stream concept in Java.

Stream methods in Java cannot be reused in general.

Once a terminal operation is performed on a stream, the stream is considered used.

Example of the Essential stream concept.

Stream<Integer> stream =

Stream.of(3, 7, 9, 12);

stream.forEach(System.out::println);

// This expression throws an exception

stream.forEach(System.out::println);

Here’s what you’ll get.

java.lang.IllegalStateException:

This user-defined stream has already been operated on, or has been closed.

Instead, you create a new stream.

import java.util.stream.Stream;

public class Main {

public static void main(String[] args) {

// First user-defined stream element

Stream<Integer> streamone = Stream.of(3, 7, 9, 11, 21);

streamone.forEach(System.out::println);

// Second user-defined stream element

Stream<Integer> streamtwo = Stream.of(3, 7, 9, 11, 21);

streamtwo.forEach(System.out::println);

}

}

Main Sources of Stream Data Creation — Detail Summary

#Collection data sourceApply stream function methodStream data type method
1.Collection data typesUse for it collection.stream() function methodUse it for Stream<T>
2.Collection elementUse collection.parallelStream() function methodUse for it Stream<T>
3.Array homogenous dataUse Arrays.stream(array) function methodUse for it Stream<T> / primitive stream
4.Values data typeUse Stream.of(…)function methodYou can use Stream<T> method
5.Empty dataWe can use Stream.empty() function methodWe apply for it Stream<T>
6.Generate stream dataWe can use Stream.generate(…)function methodWe ca apply Stream<T>
7.Iterate data methodWe can use Stream.iterate(…) function methodWe ca apply Stream<T>
8.Integers data typeWe can use IntStream.of(…) function methodWe ca apply IntStream
9.Integer range data typeWe can use IntStream.range(…) function methodWe ca apply IntStream
10.Integer range data typeWe can use IntStream.rangeClosed(…) function methodWe ca apply IntStream
11.String data typeWe can use string.chars() function methodWe ca apply IntStream
12.File data typeWe can use Files.lines(…)function methodWe ca apply Stream<String>
13.Map keys data typeWe can use map.keySet().stream() function methodWe ca apply Stream<K>
14.Map values data typeWe can use map.values().stream() function methodWe ca apply Stream<V>
15.Map entries data typeWe can use map.entrySet().stream() function methodWe ca apply Stream<Map.Entry<K,V>>

Source and details of creating streams in the Java programming language—summary.

The most important methods to remember in a Java program.

// Collection data types

list.stream();

// Array data type element

Arrays.stream(array);

// Individual data type element value

Stream.of(9, 11, 17, 20);

// Empty collection data type element

Stream.empty();

// Infinite data type generated stream

Stream.generate(() -> value);

// Infinite iterative stream data

Stream.iterate(1, num -> num + 1);

// Primitive data type element range

IntStream.range(11, 21);

// Inclusive primitive data type element Range

IntStream.rangeClosed(11, 21);

// Parallel data type element

list.parallelStream();

Stream creation in Java programming is basically as follows.

Collection data type source → Stream → Operations → Terminal operation.

Collection list/array/set/map/file data type

↓

Stream creation function and method

↓

Filter/map/sorted data element

↓

forEach/collect/reduce method

↓

Final output

Leave a Reply