Stream API in Java with Example

Stream API in Java with ExampleOverview

In this tutorial we will discuss about example of Stream API.Java 8 introduced Stream API.Stream represents a sequence of objects.Stream API support aggregate operations.To understand this topic ,you have basic knowledge of Java 8.Java Stream operations uses functional interface.

What is Stream?

Stream is sequence of objects that support aggregate operation and different type of method.

Stream API Features:-

List of few features of Java Stream API.

  1. Stream does not store any data.
  2. It is not a data structure.
  3. Stream take input from Arrays,I/O and Collections.
  4. Stream support aggregate functions like map,reduce,filter,match,limit and find.
  5. Stream operations iterates data internally.
  6. Stream does not changes any data so return result as pipelined methods.

How to create Stream?

There are different ways to create streams.Lets see an example of Stream creation.Collection interface has two methods to create a stream.

Stream API in Java with Example

  1. Array:-

The Arrays.stream() and stream.of() methods create sequential Stream from array.Both methods return stream.

  • Generate stream using stream.of:-
    Example:-

package com.javatechexpert;
import java.util.Iterator;
import java.util.stream.Stream;

public class JTE {

private static <T> void getStream(T[] arr) 
{ 


// using Stream.of() 
Stream<T> streamOfArray = Stream.of(arr); 

Iterator<T> iter = streamOfArray.iterator(); 
while (iter.hasNext()) { 
System.out.print(iter.next() + " "); 
} 
} 

public static void main(String[] args) 
{ 

String[] arr = new String[] { "java", "python", "C" }; 
getStream(arr); 
}
}


Output:- java python C
  • Generate stream using Arrays.stream():-

Example:-

package com.javatechexpert;

import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.Stream;

public class Streamarray {

private static <T> void getStream(T[] arr) 
{ 

// using Array.stream() 
Stream<T> streamOfArray = Arrays.stream(arr); 

Iterator<T> it = streamOfArray.iterator(); 

// Iterate stream object 
while (it.hasNext()) { 
System.out.print(it.next() + " "); 
} 
} 
public static void main(String[] args) 
{ 

String[] arr = new String[] { "java", "python", "C" }; 
getStream(arr); 
}

}
Output:-java python C

 

2.  Stream.empty():-

The empty() method is used to create empty stream.The empty() method is used upon creation to avoid returning null for streams with no elements.

Example:-

package com.javatechexpert;

import java.util.Arrays;
import java.util.Iterator;
import java.util.stream.Stream;

public class Emptystream {

private static void getemptyStream() 
{ 

// empty stream 
Stream streamOfArray = Stream.empty(); 

Iterator it = streamOfArray.iterator(); 
while (it.hasNext()) { 
System.out.print(it.next() + " "); 
} 
} 
public static void main(String[] args) 
{ 
getemptyStream(); 
}

}
Output:-

3. Collection:-

The collection.stream() method create a sequential stream using collection.

Example:-

package com.javatechexpert;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

public class Streamcollection {

private static <T> void getcollectionStream(List<T> list) 
{ 
// Create stream object 
Stream<T> stream = list.stream(); 
Iterator<T> iter = stream.iterator(); 
while (iter.hasNext()) { 
System.out.print(iter.next() + " "); 
} 
} 

public static void main(String[] args) 
{ 
List<String> lst = new ArrayList<>(); 
lst.add("Java"); 
lst.add("Python"); 
lst.add("C"); 

getcollectionStream(lst); 
} 
}


Output:-Java Python C

4. Stream.builder():-

The builder() method create instance of Stream object.

Example:-

package com.javatechexpert;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

public class Streambuilder {


private static <T> void getbuilderStream() 
{ 

// Create stream object 
Stream.Builder<String> builder 
= Stream.builder();


Stream<String> stream = builder.add("Java") 
.add("Python") 
.add("C") 
.build(); 

Iterator<String> iter = stream.iterator(); 
while (iter.hasNext()) { 
System.out.print(iter.next() + " "); 
} 
} 

public static void main(String[] args) 
{ 
getbuilderStream(); 
} 
}
Output:-Java Python C

 

5. Stream.generate():-

The generate method accept  supplier for generating elements and result stream is infinite.User should declare size or generate() method will work until it reaches the memory limit.

Example:-The following example creates a stream of 15 random numbers between 0 and 49.

package com.javatechexpert;

import java.util.Random;
import java.util.stream.Stream;

public class Generatestream {


public static void main(String args[]) {
Stream<Integer> randomNumbers = Stream.generate(() ->(new Random()).nextInt(50) );

randomNumbers.limit(15).forEach( System.out::println );

}
}

Output:-

13
36
29
13
29
39
24
39
1
34
41
32
28
17
19

6.  Stream.iterate():-

This is another way to create infinite stream.

Example:-

package com.javatechexpert;

import java.util.stream.Stream;

public class Iteratestream {


public static void main(String args[]) {
Stream.iterate(0, n -> n + 1)
.limit(10)
.forEach(x -> System.out.println(x));

}
}

Output:-

0
1
2
3
4
5
6
7
8
9

7. Primitives:-

You can create streams using intStream,longStream and doubleStream interface.

Example:-

package com.javatechexpert;

import java.util.Arrays;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;

public class Primitivestream {

public static void main(String args[]) {


IntStream inStrm = IntStream.of(1, 2, 3, 4);
System.out.println("----- IntStream -----");
inStrm.forEach(System.out::println);

double[] results = {18.15, 32.47, 45.40, 38.2};
DoubleStream resultStream = Arrays.stream(results);
System.out.println("----- DoubleStream -----");
resultStream.forEach(System.out::println);
}
}

Output:-

----- IntStream -----
1
2
3
4
----- DoubleStream -----
18.15
32.47
45.4
38.2

8. String:-

The chars() method of string class is used for create stream.

Example:-

package com.javatechexpert;

import java.util.stream.IntStream;

public class Primitivestream {

public static void main(String args[]) {


IntStream inStrm = "Java".chars();
System.out.println("----- charStream -----");
inStrm.forEach(System.out::println);


}
}

Output:-

----- charStream -----
74
97
118
97

Parallelstream:-

We can create parallel stream using existing stream.

 List<Integer> myList = new ArrayList<>();
for(int i=0; i<50; i++) myList.add(i);

//parallel stream
Stream<Integer> parallelStream = myList.parallelStream();

Java Stream Intermediate and Terminal Operations:-

What is Intermediate Operations?

Java Stream API that returns new Stream are called Intermediate operations.This operations are lazy.

Stream intermediate operation do not get executed until terminal operation is invoked.It allows you to call multiple operations in the form of query.

List of stream intermediate operations:-
  • map()
  • filter()
  • flatmap()
  • peek()
  • distinct()
  • sorted()
  • limit()
  • skip()

What is terminal operation?

Stream API operations that return result

It can returns primitive value or concrete type.They are eagerly executed.Terminal operation is last operation in stream pipeline.

List of Stream Terminal Operations:-
  • collect()
  • reduce()
  • foreach()
  • min()
  • max()
  • count()
  • anymatch()
  • allmatch()
  • nonematch()

Converting Java Stream to Collection or Array :-

  1. Collect():-

We can use stream collect method to get list ,map or set from Stream.

Example:-

package com.javatechexpert;

import java.util.Arrays;
import java.util.List;

public class Parallelstream {

public static void main(String[] args) {
// TODO Auto-generated method stub


List<String> list = Arrays.asList("Java", "Python", "C");
String result = list.parallelStream().collect(StringBuilder::new,
(response, element) -> response.append(" ").append(element),
(response1, response2) -> response1.append(",").append(response2.toString()))
.toString();
System.out.println(result);

}

}

Output:-

 Java, Python, C

  2. toArray():-

We can use stream toArray method to create array from Stream.

Example:-

package com.javatechexpert;

import java.util.Arrays;

public class Streamapi {

public static void main(String args[]) {

String lines = "Java 8 Stream API";

String[] result = Arrays.stream(lines.split("\\s+"))
.map(String::toUpperCase)
.toArray(String[]::new);

for (String s : result) {
System.out.println(s);
}
}
}

Output:-

JAVA
8
STREAM
API
Related Articles:-

Java 8  Interview Questions and Answers

 

Reference:

Stream API

Leave a Reply

%d bloggers like this: