0% found this document useful (0 votes)
19 views

Java 8 - Part 3 Stream

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Java 8 - Part 3 Stream

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Stream

Java provides a new additional package in Java 8 called java.util.stream. This


package consists of classes, interfaces and enum to allows functional-style
operations on the elements. You can use stream by importing java.util.stream
package.

 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

1. Stream Creation: Streams can be created from collections, arrays, or


generator functions.
2. Intermediate Operations: Operations that transform a stream into another
stream. They are lazy, meaning they are not executed until a terminal
operation is performed.
3. Terminal Operations: Operations that produce a result or a side-effect and
terminate the stream pipeline.
o Java Stream Interface Methods

Methods Description

boolean allMatch(Predicate<? super It returns all elements of this stream which


T> predicate) match the provided predicate. If the stream is
empty then true is returned and the predicate
is not evaluated.

boolean anyMatch(Predicate<? It returns any element of this stream that


super T> predicate) matches the provided predicate. If the stream
is empty then false is returned and the
predicate is not evaluated.

static <T> Stream.Builder<T> It returns a builder for a Stream.


builder()

<R,A> R collect(Collector<? super It performs a mutable reduction operation on


T,A,R> collector) the elements of this stream using a Collector. A
Collector encapsulates the functions used as
arguments to collect(Supplier, BiConsumer,
BiConsumer), allowing for reuse of collection
strategies and composition of collect
operations such as multiple-level grouping or
partitioning.

<R> R collect(Supplier<R> supplier, It performs a mutable reduction operation on


BiConsumer<R,? super T> the elements of this stream. A mutable
accumulator, BiConsumer<R,R> reduction is one in which the reduced value is a
combiner) mutable result container, such as an ArrayList,
and elements are incorporated by updating the
state of the result rather than by replacing the
result.

static <T> Stream<T> It creates a lazily concatenated stream whose


concat(Stream<? extends T> a, elements are all the elements of the first
Stream<? extends T> b) stream followed by all the elements of the
second stream. The resulting stream is ordered
if both of the input streams are ordered, and
parallel if either of the input streams is parallel.
When the resulting stream is closed, the close
handlers for both input streams are invoked.

long count() It returns the count of elements in this stream.


This is a special case of a reduction.

Stream<T> distinct() It returns a stream consisting of the distinct


elements (according to Object.equals(Object))
of this stream.
static <T> Stream<T> empty() It returns an empty sequential Stream.

Stream<T> filter(Predicate<? super It returns a stream consisting of the elements


T> predicate) of this stream that match the given predicate.

Optional<T> findAny() It returns an Optional describing some element


of the stream, or an empty Optional if the
stream is empty.

Optional<T> findFirst() It returns an Optional describing the first


element of this stream, or an empty Optional if
the stream is empty. If the stream has no
encounter order, then any element may be
returned.

<R> Stream<R> It returns a stream consisting of the results of


flatMap(Function<? super T,? replacing each element of this stream with the
extends Stream<? extends R>> contents of a mapped stream produced by
mapper) applying the provided mapping function to
each element. Each mapped stream is closed
after its contents have been placed into this
stream. (If a mapped stream is null an empty
stream is used, instead.)

DoubleStream It returns a DoubleStream consisting of the


flatMapToDouble(Function<? super results of replacing each element of this
T,? extends DoubleStream> stream with the contents of a mapped stream
mapper) produced by applying the provided mapping
function to each element. Each mapped stream
is closed after its contents have placed been
into this stream. (If a mapped stream is null an
empty stream is used, instead.)

IntStream flatMapToInt(Function<? It returns an IntStream consisting of the results


super T,? extends IntStream> of replacing each element of this stream with
mapper) the contents of a mapped stream produced by
applying the provided mapping function to
each element. Each mapped stream is closed
after its contents have been placed into this
stream. (If a mapped stream is null an empty
stream is used, instead.)

LongStream It returns a LongStream consisting of the


flatMapToLong(Function<? super T,? results of replacing each element of this
extends LongStream> mapper) stream with the contents of a mapped stream
produced by applying the provided mapping
function to each element. Each mapped stream
is closed after its contents have been placed
into this stream. (If a mapped stream is null an
empty stream is used, instead.)
void forEach(Consumer<? super T> It performs an action for each element of this
action) stream.

void forEachOrdered(Consumer<? It performs an action for each element of this


super T> action) stream, in the encounter order of the stream if
the stream has a defined encounter order.

static <T> Stream<T> It returns an infinite sequential unordered


generate(Supplier<T> s) stream where each element is generated by
the provided Supplier. This is suitable for
generating constant streams, streams of
random elements, etc.

static <T> Stream<T> iterate(T It returns an infinite sequential ordered Stream


seed,UnaryOperator<T> f) produced by iterative application of a function f
to an initial element seed, producing a Stream
consisting of seed, f(seed), f(f(seed)), etc.

Stream<T> limit(long maxSize) It returns a stream consisting of the elements


of this stream, truncated to be no longer than
maxSize in length.

<R> Stream<R> map(Function<? It returns a stream consisting of the results of


super T,? extends R> mapper) applying the given function to the elements of
this stream.

DoubleStream It returns a DoubleStream consisting of the


mapToDouble(ToDoubleFunction<? results of applying the given function to the
super T> mapper) elements of this stream.

IntStream It returns an IntStream consisting of the results


mapToInt(ToIntFunction<? super T> of applying the given function to the elements
mapper) of this stream.

LongStream It returns a LongStream consisting of the


mapToLong(ToLongFunction<? results of applying the given function to the
super T> mapper) elements of this stream.

Optional<T> max(Comparator<? It returns the maximum element of this stream


super T> comparator) according to the provided Comparator. This is a
special case of a reduction.

Optional<T> min(Comparator<? It returns the minimum element of this stream


super T> comparator) according to the provided Comparator. This is a
special case of a reduction.

boolean noneMatch(Predicate<? It returns elements of this stream match the


super T> predicate) provided predicate. If the stream is empty then
true is returned and the predicate is not
evaluated.
@SafeVarargs static <T> It returns a sequential ordered stream whose
Stream<T> of(T... values) elements are the specified values.

static <T> Stream<T> of(T t) It returns a sequential Stream containing a


single element.

Stream<T> peek(Consumer<? It returns a stream consisting of the elements


super T> action) of this stream, additionally performing the
provided action on each element as elements
are consumed from the resulting stream.

Optional<T> It performs a reduction on the elements of this


reduce(BinaryOperator<T> stream, using an associative accumulation
accumulator) function, and returns an Optional describing
the reduced value, if any.

T reduce(T identity, It performs a reduction on the elements of this


BinaryOperator<T> accumulator) stream, using the provided identity value and
an associative accumulation function, and
returns the reduced value.

<U> U reduce(U identity, It performs a reduction on the elements of this


BiFunction<U,? super T,U> stream, using the provided identity,
accumulator, BinaryOperator<U> accumulation and combining functions.
combiner)

Stream<T> skip(long n) It returns a stream consisting of the remaining


elements of this stream after discarding the
first n elements of the stream. If this stream
contains fewer than n elements then an empty
stream will be returned.

Stream<T> sorted() It returns a stream consisting of the elements


of this stream, sorted according to natural
order. If the elements of this stream are not
Comparable, a java.lang.ClassCastException
may be thrown when the terminal operation is
executed.

Stream<T> sorted(Comparator<? It returns a stream consisting of the elements


super T> comparator) of this stream, sorted according to the provided
Comparator.

Object[] toArray() It returns an array containing the elements of


this stream.

<A> A[] toArray(IntFunction<A[]> It returns an array containing the elements of


generator) this stream, using the provided generator
function to allocate the returned array, as well
as any additional arrays that might be required
for a partitioned execution or for resizing.

Java Example: Filtering Collection without using Stream


In the following example, we are filtering data without using stream. This approach
we are used before the stream package was released.

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:

[25000.0, 28000.0, 28000.0]

Java Stream Example: Filtering Collection by using Stream


Here, we are filtering data by using stream. You can see that code is optimized and
maintained. Stream provides fast execution.

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]

Java Stream Filter


Java stream provides a method filter() to filter stream elements on the basis of
given predicate. Suppose you want to get only even elements of your list then you
can do this easily with the help of filter method.

This method takes predicate as an argument and returns a stream of consisting of


resulted elements.

Signature
The signature of Stream filter() method is given below:

1. Stream<T> filter(Predicate<? super T> predicate)

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.

Java Stream filter() example


In the following example, we are fetching and iterating filtered data.

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

Java Stream Iterating Example


You can use stream to iterate any number of times. Stream provides predefined
methods to deal with the logic you implement. In the following example, we are
iterating, filtering and passed a limit to fix the iteration.

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

Java Stream Example: Filtering and Iterating Collection


In the following example, we are using filter() method. Here, you can see code is
optimized and very concise.

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

Java Stream Example : reduce() Method in Collection


This method takes a sequence of input elements and combines them into a single
summary result by repeated operation. For example, finding the sum of numbers, or
accumulating elements into a list.

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

Java Stream Example: Sum by using Collectors Methods


We can also use collectors to compute sum of numeric values. In the following
example, we are using Collectors class and it?s specified methods to compute sum
of all the product prices.

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

Java Stream Example: Find Max and Min Product Price


Following example finds min and max product price by using stream. It provides
convenient way to find values without using imperative approach.

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

Java Stream Example: count() Method in Collection


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. // count number of products based on the filter
22. long count = productsList.stream()
23. .filter(product->product.price<30000)
24. .count();
25. System.out.println(count);
26. }
27.}

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.

Java Stream Example : Convert List into Set


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.
14.public class JavaStreamExample {
15. public static void main(String[] args) {
16. List<Product> productsList = new ArrayList<Product>();
17.
18. //Adding Products
19. productsList.add(new Product(1,"HP Laptop",25000f));
20. productsList.add(new Product(2,"Dell Laptop",30000f));
21. productsList.add(new Product(3,"Lenevo Laptop",28000f));
22. productsList.add(new Product(4,"Sony Laptop",28000f));
23. productsList.add(new Product(5,"Apple Laptop",90000f));
24.
25. // Converting product List into Set
26. Set<Float> productPriceList =
27. productsList.stream()
28. .filter(product->product.price < 30000) // filter product on the base of price

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]

Java Stream Example : Convert List into Map


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.
14.public class JavaStreamExample {
15. public static void main(String[] args) {
16. List<Product> productsList = new ArrayList<Product>();
17.
18. //Adding Products
19. productsList.add(new Product(1,"HP Laptop",25000f));
20. productsList.add(new Product(2,"Dell Laptop",30000f));
21. productsList.add(new Product(3,"Lenevo Laptop",28000f));
22. productsList.add(new Product(4,"Sony Laptop",28000f));
23. productsList.add(new Product(5,"Apple Laptop",90000f));
24.
25. // Converting Product List into a Map
26. Map<Integer,String> productPriceMap =
27. productsList.stream()
28. .collect(Collectors.toMap(p->p.id, p->p.name));
29.
30. System.out.println(productPriceMap);
31. }
32.}

Output:

{1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop}

Method Reference in stream


1. import java.util.*;
2. import java.util.stream.Collectors;
3.
4. class Product{
5. int id;
6. String name;
7. float price;
8.
9. public Product(int id, String name, float price) {
10. this.id = id;
11. this.name = name;
12. this.price = price;
13. }
14.
15. public int getId() {
16. return id;
17. }
18. public String getName() {
19. return name;
20. }
21. public float getPrice() {
22. return price;
23. }
24.}
25.
26.public class JavaStreamExample {
27.
28. public static void main(String[] args) {
29.
30. List<Product> productsList = new ArrayList<Product>();
31.
32. //Adding Products
33. productsList.add(new Product(1,"HP Laptop",25000f));
34. productsList.add(new Product(2,"Dell Laptop",30000f));
35. productsList.add(new Product(3,"Lenevo Laptop",28000f));
36. productsList.add(new Product(4,"Sony Laptop",28000f));
37. productsList.add(new Product(5,"Apple Laptop",90000f));
38.
39. List<Float> productPriceList =
40. productsList.stream()
41. .filter(p -> p.price > 30000) // filtering data
42. .map(Product::getPrice) // fetching price by referring getPrice
method
43. .collect(Collectors.toList()); // collecting as list
44. System.out.println(productPriceList);
45. }
46.}
Output:

[90000.0

package Java8.Stream;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JamesJJ {

public static void main(String[] args)


{

List<String> list = Arrays.asList("ranjini", "mani", "kalees",


"mithu", "thuki");

List<String> str = list.stream()


.filter(name -> name.startsWith("m"))
.map(name -> name.concat("first"))
.collect(Collectors.toList());
System.out.println(str);

List<Integer> arr = new ArrayList<>(Arrays.asList(1, 1, 7, 8, 5, 5, 4,


3, 3, 8));

List<Integer> arr1 = arr.stream().map(value -> value *


10).collect(Collectors.toList());

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("duplicate removed list");


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

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());

System.out.println("skip result " + skipresult);

char b[] = {'D', 'A', 'C', 'B'};


List<char[]> li = Arrays.asList(b);

li.stream().parallel().forEach(t -> System.out.println(t));

li.stream().parallel().forEachOrdered(t -> System.out.println(t));

long counti = arr.stream().count();


System.out.println(counti);

Optional<Integer> minnumber =
arr.stream().min(Comparator.naturalOrder());
System.out.println("minimum of the list " + minnumber.get());

System.out.println("maximum number is " +


arr.stream().max(Comparator.naturalOrder()).get());

System.out.println(arr.stream().findFirst().get());

Stream<Integer> strm = Stream.of(1, 2, 2, 5, 7);

System.out.println(strm.findAny().get());

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


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

//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);

Optional<Integer> t = totalList.stream().flatMap(val ->


val.stream())//[1,2,3,4,5,6,7,8,9,10,11,12]
.distinct().reduce(Integer::max);//.collect(Collectors.toList(
));
System.out.println(t.get());

Integer t1 = totalList.stream().flatMap(val ->


val.stream())//[1,2,3,4,5,6,7,8,9,10,11,12]
.distinct().reduce(Integer::max).get();//.collect(Collectors.t
oList());
System.out.println(t1);
}
}

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

Process finished with exit code 0


Basic Usage

Stream Creation

 From Collections

List<String> list = Arrays.asList("a", "b", "c");


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

 From Arrays

String[] array = {"a", "b", "c"};


Stream<String> stream = Arrays.stream(array);

 Using Stream.of

Stream<String> stream = Stream.of("a", "b", "c");

 Infinite Streams

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


Stream<Integer> evenNumbers = Stream.iterate(0, n -> n + 2);

Intermediate Operations

 Filtering

List<String> list = Arrays.asList("a", "b", "c", "aa", "bb");


List<String> result = list.stream()
.filter(s -> s.startsWith("a"))
.collect(Collectors.toList());

 Mapping

List<String> list = Arrays.asList("a", "b", "c");


List<String> result = list.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());

 Sorting

List<String> list = Arrays.asList("b", "a", "c");


List<String> result = list.stream()
.sorted()
.collect(Collectors.toList());

 Distinct
List<String> list = Arrays.asList("a", "b", "a");
List<String> result = list.stream()
.distinct()
.collect(Collectors.toList());

 Limit and Skip

List<String> list = Arrays.asList("a", "b", "c", "d");


List<String> result = list.stream()
.skip(1)
.limit(2)
.collect(Collectors.toList());

Terminal Operations

 Collect

List<String> list = Arrays.asList("a", "b", "c");


List<String> result = list.stream()
.collect(Collectors.toList());

 ForEach

List<String> list = Arrays.asList("a", "b", "c");


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

 Reduce

List<Integer> list = Arrays.asList(1, 2, 3);


int sum = list.stream()
.reduce(0, Integer::sum);

 Count

List<String> list = Arrays.asList("a", "b", "c");


long count = list.stream().count();

 Find First / Find Any

List<String> list = Arrays.asList("a", "b", "c");


Optional<String> first = list.stream().findFirst();
Optional<String> any = list.stream().findAny();

 Match

List<String> list = Arrays.asList("a", "b", "c");


boolean anyStartsWithA = list.stream().anyMatch(s -> s.startsWith("a"));
boolean allStartWithA = list.stream().allMatch(s -> s.startsWith("a"));
boolean noneStartWithZ = list.stream().noneMatch(s ->
s.startsWith("z"));
Example

Here's a complete example combining multiple operations:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {


public static void main(String[] args) {
List<String> list = Arrays.asList("abc", "bcd", "cde", "def", "efg");

List<String> result = list.stream()


.filter(s -> s.contains("e"))
.map(String::toUpperCase)
.sorted()
.distinct()
.collect(Collectors.toList());

System.out.println(result);
}
}

This code will output:

[CDE, DEF, EFG]

You might also like