Java 8 - Part 3 Stream
Java 8 - Part 3 Stream
Stream Does Not Store Elements: A stream doesn't keep the data it processes. Instead, it
takes elements from a source (like a list or an array) and processes them through a series of
operations.
Functional Nature: Streams work in a way that doesn't change the original data. For
example, if you filter elements from a stream based on a condition, the original collection
remains unchanged. The stream gives you a new collection with only the filtered elements.
Laziness: Streams do not do any processing until it is absolutely necessary. They wait until
the final result is needed before performing any operations.
Single Pass: Each element in a stream is processed only once. If you need to process the same
elements again, you have to create a new stream.
Usage: You can use streams to perform various tasks like filtering data, collecting data into a
different form, printing data, or converting data from one structure to another.
Stream Pipeline
A stream pipeline consists of a source, zero or more intermediate operations, and a terminal
operation:
Key Concepts
Methods Description
1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11.}
12.public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. List<Float> productPriceList = new ArrayList<Float>();
22. for(Product product: productsList){
23.
24. // filtering data of list
25. if(product.price<30000){
26. productPriceList.add(product.price); // adding price to a productPriceList
27. }
28. }
29. System.out.println(productPriceList); // displaying data
30. }
31.}
Output:
1. import java.util.*;
2. import java.util.stream.Collectors;
3. class Product{
4. int id;
5. String name;
6. float price;
7. public Product(int id, String name, float price) {
8. this.id = id;
9. this.name = name;
10. this.price = price;
11. }
12.}
13.public class JavaStreamExample {
14. public static void main(String[] args) {
15. List<Product> productsList = new ArrayList<Product>();
16. //Adding Products
17. productsList.add(new Product(1,"HP Laptop",25000f));
18. productsList.add(new Product(2,"Dell Laptop",30000f));
19. productsList.add(new Product(3,"Lenevo Laptop",28000f));
20. productsList.add(new Product(4,"Sony Laptop",28000f));
21. productsList.add(new Product(5,"Apple Laptop",90000f));
22. List<Float> productPriceList2 =productsList.stream()
23. .filter(p -> p.price > 30000)// filtering data
24. .map(p->p.price) // fetching price
25. .collect(Collectors.toList()); // collecting as list
26. System.out.println(productPriceList2);
27. }
28.}
Output:
[90000.0]
Signature
The signature of Stream filter() method is given below:
Parameter
predicate: It takes Predicate reference as an argument. Predicate is a functional
interface. So, you can also pass lambda expression here.
Return
It returns a new stream.
1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11.}
12.public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. productsList.stream()
22. .filter(p ->p.price> 30000) // filtering price
23. .map(pm ->pm.price) // fetching price
24. .forEach(System.out::println); // iterating price
25. }
26.}
Output:
90000.0
1. import java.util.stream.*;
2. public class JavaStreamExample {
3. public static void main(String[] args){
4. Stream.iterate(1, element->element+1)
5. .filter(element->element%5==0)
6. .limit(5)
7. .forEach(System.out::println);
8. }
9. }
Output:
5
10
15
20
25
1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11.}
12.public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. // This is more compact approach for filtering data
22. productsList.stream()
23. .filter(product -> product.price == 30000)
24. .forEach(product -> System.out.println(product.name));
25. }
26.}
Output:
Dell Laptop
In the following example, we are using reduce() method, which is used to sum of all
the product prices.
1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11.}
12.public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. // This is more compact approach for filtering data
22. Float totalPrice = productsList.stream()
23. .map(product->product.price)
24. .reduce(0.0f,(sum, price)->sum+price); // accumulating price
25. System.out.println(totalPrice);
26. // More precise code
27. float totalPrice2 = productsList.stream()
28. .map(product->product.price)
29. .reduce(0.0f,Float::sum); // accumulating price, by referring method of Fl
oat class
30. System.out.println(totalPrice2);
31.
32. }
33.}
Output:
201000.0
201000.0
1. import java.util.*;
2. import java.util.stream.Collectors;
3. class Product{
4. int id;
5. String name;
6. float price;
7. public Product(int id, String name, float price) {
8. this.id = id;
9. this.name = name;
10. this.price = price;
11. }
12.}
13.public class JavaStreamExample {
14. public static void main(String[] args) {
15. List<Product> productsList = new ArrayList<Product>();
16. //Adding Products
17. productsList.add(new Product(1,"HP Laptop",25000f));
18. productsList.add(new Product(2,"Dell Laptop",30000f));
19. productsList.add(new Product(3,"Lenevo Laptop",28000f));
20. productsList.add(new Product(4,"Sony Laptop",28000f));
21. productsList.add(new Product(5,"Apple Laptop",90000f));
22. // Using Collectors's method to sum the prices.
23. double totalPrice3 = productsList.stream()
24. .collect(Collectors.summingDouble(product->product.price));
25. System.out.println(totalPrice3);
26.
27. }
28.}
Output:
201000.0
1. import java.util.*;
2. class Product{
3. int id;
4. String name;
5. float price;
6. public Product(int id, String name, float price) {
7. this.id = id;
8. this.name = name;
9. this.price = price;
10. }
11.}
12.public class JavaStreamExample {
13. public static void main(String[] args) {
14. List<Product> productsList = new ArrayList<Product>();
15. //Adding Products
16. productsList.add(new Product(1,"HP Laptop",25000f));
17. productsList.add(new Product(2,"Dell Laptop",30000f));
18. productsList.add(new Product(3,"Lenevo Laptop",28000f));
19. productsList.add(new Product(4,"Sony Laptop",28000f));
20. productsList.add(new Product(5,"Apple Laptop",90000f));
21. // max() method to get max Product price
22. Product productA = productsList.stream().max((product1, product2)-
>product1.price > product2.price ? 1: -1).get();
23. System.out.println(productA.price);
24. // min() method to get min Product price
25. Product productB = productsList.stream().min((product1, product2)-
>product1.price > product2.price ? 1: -1).get();
26. System.out.println(productB.price);
27.
28. }
29.}
Output:
90000.0
25000.0
Output:
stream allows you to collect your result in any various forms. You can get you result
as set, list or map and can perform manipulation on the elements.
29. .map(product->product.price)
30. .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements)
31. System.out.println(productPriceList);
32. }
33.}
Output:
[25000.0, 28000.0]
Output:
{1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop}
[90000.0
package Java8.Stream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
System.out.println(Arrays.toString(arr1.toArray()));
System.out.println(arr1);
System.out.println(arr1.contains(10));
System.out.println("Ascending order");
arr.stream().sorted().forEach(System.out::println);
System.out.println("Deseding order");
// Stream<Integer> a = arr.stream();
arr.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);//
forEach(y->System.out.println(y));
System.out.println("limit result");
List<Integer> ans =
arr.stream().limit(4).collect(Collectors.toList());
System.out.println(ans);
List<Integer> skipresult =
arr.stream().skip(3).collect(Collectors.toList());
Optional<Integer> minnumber =
arr.stream().min(Comparator.naturalOrder());
System.out.println("minimum of the list " + minnumber.get());
System.out.println(arr.stream().findFirst().get());
System.out.println(strm.findAny().get());
//flatMap
List<Integer> a1 = Arrays.asList(1, 2, 3);
List<Integer> a2 = Arrays.asList(4, 5, 6);
List<Integer> a3 = Arrays.asList(7, 8, 9);
List<Integer> a4 = Arrays.asList(10, 11, 12);
List<List<Integer>> totalList = Arrays.asList(a1, a2, a3, a4);
// System.out.println(a1+" "+a2);
// System.out.println(totalList);
Output:
[manifirst, mithufirst]
[10, 10, 70, 80, 50, 50, 40, 30, 30, 80]
[10, 10, 70, 80, 50, 50, 40, 30, 30, 80]
true
Ascending order
1
1
3
3
4
5
5
7
8
8
Deseding order
8
8
7
5
5
4
3
3
1
1
duplicate removed list
1
7
8
5
4
3
limit result
[1, 1, 7, 8]
skip result [8, 5, 5, 4, 3, 3, 8]
DACB
DACB
10
minimum of the list 1
maximum number is 8
1
1
0
12
12
Stream Creation
From Collections
From Arrays
Using Stream.of
Infinite Streams
Intermediate Operations
Filtering
Mapping
Sorting
Distinct
List<String> list = Arrays.asList("a", "b", "a");
List<String> result = list.stream()
.distinct()
.collect(Collectors.toList());
Terminal Operations
Collect
ForEach
Reduce
Count
Match
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
System.out.println(result);
}
}