In this blog post we will talk and learn about one of very important java 8 interview question and question is that Explain Stream API introduced in Java 8 ?
What is a Stream ?
- A stream can be define as a sequence of data elements supporting sequential and parallel aggregate operations.
- Example like computing the sum of all elements in a stream of integers, mapping all names in list to their lengths, aggregate operations on streams etc..
How is it different than Collection ?
Collections focus on the storage of data elements for efficient access whereas streams focus on aggregate computations on data elements from a data source.
Few Important key points about Stream are –
- Streams have no storage.
- Streams can represent a sequence of infinite elements.
- The design of streams is based on internal iteration.
- Streams are designed to be processed in parallel with no additional work from the developers.
- Streams are designed to support functional programming.
- Streams support lazy operations.
- Streams can be ordered or unordered.
- Streams cannot be reused.
What is ParallelStream ?
Java provides two main functionalities out of the box –
a)Partitioning of the stream of data into smaller streams to make parallel processing possible.
b)Parallel processing of the data
Can you provide some example of Stream API?
Creating Stream from Values
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.kkjavatutorials.client; import java.util.stream.IntStream; import java.util.stream.Stream; /** * @author KK JavaTutorials * Creating Stream from Values */ public class StreamApiExample_1 { public static void main(String[] args) { /* * Creating a Stream * We can create Streams in multiple ways - */ //1.Stream from Values System.out.println("Strem of Strings......"); Stream<String> stringStream = Stream.of("John", "Sean", "Sam", "Bingel"); stringStream.forEach(System.out::println); System.out.println("Stream of Integers......"); Stream<Integer> integerStream = Stream.of(10, 20, 30, 40, 50); integerStream.forEach(System.out::println); System.out.println("Stream of finite Integers......"); IntStream oneToTen = IntStream.range(1, 11); oneToTen.forEach(System.out::println); } } |
Output:
Stream of Strings……
John
Sean
Sam
Bingel
Stream of Integers……
10
20
30
40
50
Stream of finite Integers……
1
2
3
4
5
6
7
8
9
10
Stream Functions example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.kkjavatutorials.client; import java.util.stream.Stream; /** * @author KK JavaTutorials *Stream Functions example */ public class StreamApiExample_2 { public static void main(String[] args) { /* * Creating a Stream * We can create Streams in multiple ways - */ //2.Stream from Functions //printOddNumbers(); printFirstFiveOddNumbers(); printFiveRandomNumbers(); } private static void printFiveRandomNumbers() { System.out.println("Getting first five random numbers using Stream.."); Stream.generate(Math::random).limit(5).forEach(System.out::println); } private static void printFirstFiveOddNumbers() { System.out.println("Getting first five odd numbers using Stream.."); Stream.iterate(1L, n -> n + 2).limit(5).forEach(System.out::println); } private static void printOddNumbers() { Stream<Long> oddNumberStreams = Stream.iterate(1L, n -> n + 2); oddNumberStreams.forEachOrdered(System.out::println); } } |
Output:
Getting first five odd numbers using Stream..
1
3
5
7
9
Getting first five random numbers using Stream..
0.8260326471627876
0.9341251235732477
0.8863277196070732
0.7915521185380437
0.34936404210516936
Creating Stream from Arrays and Collections
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.kkjavatutorials.client; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.IntStream; import java.util.stream.Stream; /** * @author KK JavaTutorials *Creating Stream from Arrays and Collections */ public class StreamApiExample_3 { public static void main(String[] args) { /* * Creating a Stream * We can create Streams in multiple ways - */ //3.Stream from Arrays and Collections //Stream from Arrays System.out.println("Getting Stream from array.."); IntStream numbers = Arrays.stream(new int[]{100, 200, 300,400,500,600}); numbers.forEach(System.out::println); //Square all the numbers in the array System.out.println("Getting Square all the numbers in the array using Stream.."); IntStream.rangeClosed(1, 5) .map(n -> n * n) .forEach(System.out::println); //Stream from Collections // Create and populate a set of strings Set<String> set = new HashSet<>(); set.add("Sean"); set.add("Marry"); System.out.println("Create a sequential stream from the set.."); Stream<String> sequentialStream = set.stream(); sequentialStream.forEach(System.out::println); System.out.println("Create a parallel stream from the set"); Stream<String> parallelStream = set.parallelStream(); parallelStream.forEach(System.out::println); System.out.println("Reading file content using Stream..."); //Stream from Files Stream<String> lines = null; try { lines = Files.lines(Paths.get("test.txt")); lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); }finally { if(lines != null) lines.close(); } } } |
Output:
Getting Stream from array..
100
200
300
400
500
600
Getting Square all the numbers in the array using Stream..
1
4
9
16
25
Create a sequential stream from the set..
Sean
Marry
Create a parallel stream from the set
Sean
Marry
Reading file content using Stream…
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
Operations on Streams (Bulk Operations, Map and Reduce)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.kkjavatutorials.client; import java.util.stream.IntStream; /** * @author KK JavaTutorials *Operations on Streams (Bulk Operations, Map and Reduce) */ public class StreamApiExample_4 { public static void main(String[] args) { /* * We can create a Stream in multiple ways - */ // 4.Operations on Streams (Bulk Operations, Map and Reduce) //Take Odd numbers from the stream square them and them add them all int sum = IntStream.of(1, 2, 3, 4, 5,7) .peek(e -> System.out.println("Taking integer: " + e)) .filter(n -> n % 2 == 1) .peek(e -> System.out.println("Filtered integer: " + e)) .map(n -> n * n) .peek(e -> System.out.println("Mapped integer: " + e)) .reduce(0, Integer::sum); System.out.println("sum = " + sum); } } |
Output:
Taking integer: 1
Filtered integer: 1
Mapped integer: 1
Taking integer: 2
Taking integer: 3
Filtered integer: 3
Mapped integer: 9
Taking integer: 4
Taking integer: 5
Filtered integer: 5
Mapped integer: 25
Taking integer: 7
Filtered integer: 7
Mapped integer: 49
sum = 84
Second Example of Operations on Streams (Bulk Operations, Map and Reduce)
Employee.java class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.kkjavatutorials.model; public class Employee { private int id; private String name; private boolean isFemale; private boolean isMale; private Double salary; public Employee(int id, String name, boolean isFemale, boolean isMale, Double salary) { super(); this.id = id; this.name = name; this.isFemale = isFemale; this.isMale = isMale; this.salary = salary; } public int getId() { return id; } public String getName() { return name; } public boolean isFemale() { return isFemale; } public boolean isMale() { return isMale; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", isFemale=" + isFemale + ", isMale=" + isMale + ", salary=" + salary + "]"; } } |
Content of test.txt file
1 2 3 4 5 6 7 8 9 10 |
This is line 1 This is line 2 This is line 3 This is line 4 This is line 5 This is line 6 This is line 7 This is line 8 This is line 9 This is line 10 |
Client program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
package com.kkjavatutorials.client; import java.util.ArrayList; import java.util.List; import com.kkjavatutorials.model.Employee; /** * @author KK JavaTutorials *Operations on Streams (Bulk Operations, Map and Reduce) */ public class StreamApiExample_5 { public static void main(String[] args) { /* * We can create a Stream in multiple ways - */ // 4.Operations on Streams (Bulk Operations, Map and Reduce) Employee employee1 = new Employee(1002, "Sean", false, true, 10000.00); Employee employee2 = new Employee(1072, "Marry", true, false, 15000.00); Employee employee3 = new Employee(1882, "Sam", false, true, 30000.00); Employee employee4 = new Employee(1992, "Sofiya", true, false, 3000.00); Employee employee5 = new Employee(1112, "Raj", false, true, 16000.00); Employee employee6 = new Employee(1772, "Hema", true, false, 9000.00); List<Employee> empList = new ArrayList<>(); empList.add(employee1); empList.add(employee2); empList.add(employee3); empList.add(employee4); empList.add(employee5); empList.add(employee6); System.out.println("Get All males having income greater than 10000"); empList.stream().filter(e -> e.isMale() && e.getSalary() > 10000.0) .map(Employee::getName) .forEach(System.out::println); System.out.println("Get Combined Income of All Employees"); double totalSalary = empList.stream() .map(Employee::getSalary) .reduce(0.0, Double::sum); System.out.println(totalSalary); System.out.println("Increase Income of All Females by 10%"); empList.stream().filter(Employee::isFemale).forEach(e -> e.setSalary(e.getSalary() * 1.10)); empList.forEach(System.out::println); } } |
Output:
Get All males having income greater than 10000
Sam
Raj
Get Combined Income of All Employees
83000.0
Increase Income of All Females by 10%
Employee [id=1002, name=Sean, isFemale=false, isMale=true, salary=10000.0]
Employee [id=1072, name=Marry, isFemale=true, isMale=false, salary=16500.0]
Employee [id=1882, name=Sam, isFemale=false, isMale=true, salary=30000.0]
Employee [id=1992, name=Sofiya, isFemale=true, isMale=false, salary=3300.0000000000005]
Employee [id=1112, name=Raj, isFemale=false, isMale=true, salary=16000.0]
Employee [id=1772, name=Hema, isFemale=true, isMale=false, salary=9900.0]
That’s all about Explain Stream API introduced in Java 8 ?
You May Also Like:
What are new Features added in Java 8?
How to Convert List to Map using Java 8
Java Spliterator Example
Differences Between map() And flatMap() in Java 8 ?
How will you find Word Frequency in sorted order for a collection of words
If you have any feedback or suggestion please feel free to drop in blow comment box.