Stream API Tutorial In Java 8

Stream API are designed to be efficient and can support improving the performance of programs. We can avoid unnecessary loops and iterations in our programs by using Stream functionality. Streams can be used for filtering, collecting, printing, and converting data from one structure to another such as one collection to another collection.

  1. What is Stream API In Java 8?
  2. Operations Types In Java 8 Stream API
  3. filter() Method Example In Java 8 Stream API
  4. map() Method Example In Java 8 Stream API
  5. sorted() Method Example In Java 8 Stream API
  6. forEach() Method Example In Java 8 Stream
  7. collect() Method Example In Java 8 Stream API
  8. anyMatch() Method Example In Java 8 Stream API
  9. allMatch() Method Example In Java 8 Stream API
  10. count() Method Example In Java 8 Stream API
  11. reduce() Method Example In Java 8 Stream API
  12. findFirst() Method Example In Java 8 Stream API
  13. accept() and andThen() Method Example In Java 8 Stream API
  14. Predicate and() Method Example In Java 8 Stream API
  15. Predicate isEqual() Method Example In Java 8 Stream API
  16. Predicate negate() Method Example In Java 8 Stream API
  17. Predicate or() Method Example In Java 8 Stream API
  18. Predicate test() Method Example In Java 8 Stream API

What is Stream API In Java 8?

Stream API are designed to be efficient and can support improving the performance of programs. We can avoid unnecessary loops and iterations in our programs by using Stream functionality. Streams can be used for filtering, collecting, printing, and converting data from one structure to another such as one collection to another collection.

  1. Java 8 introduces Stream API, and some additional features to allows functional-style operations on the elements.
  2. The stream can be used by importing java.util.stream package.
  3. The stream API is used to process collections of objects.
  4. A Stream is a sequence of components that can be processed sequentially.
  5. The elements of a stream are only visited once during the life of a stream.
  6. Stream does not modify the source. It produces a new Stream by filtering or applying any logic.

Syntax:

Stream stream  = collection.strim();

Example of filterig data using stream:


import java.io.*;
import java.util.*;
import java.util.stream.*;

public class StreamFilterExample {
  static void main (String args[]){ 
    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    //Filtering the even numbers from a collection
    List<Integer> evenList = 
        Arrays.asList(numbers).stream() 
            .filter(i -> i % 2 == 0)
            .collect(Collectors.toList());
                  
    System.out.println( "Even numbers after stream operation : "+ evenList );         
          
 }
}
 

Output:
    Even numbers after stream operation : [2, 4, 6, 8, 10]

Operations Types In Java Stream API

There are mainly 3 types of operations.

  1. Intermediate operations
  2. The intermediate operation returns another stream as a result, they can be chained together to form a pipeline of operations.
    - filter()
    Filter the elements based on a specified condition. details...
    - map()
    Transforms each of the elements in a stream to another value. details...
    - sorted()
    Sorts the elements of a stream. details...
  3. Terminal operations
  4. The terminal operation means after calling this method on Stream, you cannot call any other method on Stream.
    - forEach()
    It iterates all the elements in a stream.  details...
    - collect()
    The stream.collect() method accumulate elements of any Stream into a Collection, it is a part of stream terminal operation. The Collector class provides different methods like toList(), toSet(), toMap(), and toConcurrentMap() to collect the result of Stream into List, Set, Map, and ConcurrentMap in Java. It accepts a Collector in arguments to accumulate elements of Stream into a specified Collection such as stream().collect(Collectors.toList()).  details...
    - anyMatch() and allMatch()
    The anyMatch operation checks if any element of a stream matches a given condition, while the allMatch operation checks if all elements   satisfy the given condition.  details...
    - count()
    The count operation returns the number of elements in a stream as a long value details...
    - reduce()
    It is used to reduce the elements of a stream to a single value. details...
  5. Short-circuit operations
  6. - findFirst()
    The findFirst() method finds the first element in a Stream. we use this method when we specifically want the first element from a   sequence. details...
    - anyMatch()
    It checks the stream if it satisfies the given condition. details...

filter() Method Example In Java

The stream filter() method provides the functionality to filter stream's elements on the basis of given lambda expression or predicate. The stream filter() method expects a lambda expression or predicate in argument and the lambda expression returns a boolean(true/false) value, based on boolean value filter method filters the elements.

  1. filter() is an intermediate stream operation.
  2. filter method expects a lambda expression or predicate in argument.
  3. The Predicate. is a functional interface. So, you can also pass lambda expression here.
  4. filter() method does not change/modify the original source/collection.
  5. filter() method creates a new collection(list/array) based on the condition and returns the new collection.
  6. Stream does not modify the source. It produces a new Stream by filtering or applying any logic.

Syntax:

Stream<T> filter(Predicate predicate) 

Example of filterig data using Lambda Expression in arguments

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class FilterExample {
  static void main ( String args[]) {

  Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  //Filtering the even numbers from a collection
  List<Integer> evenList = 
    Arrays.asList(numbers)
        .stream()
        //passing lambda expression in argument
        .filter(i -> i % 2 == 0)
        .collect(Collectors.toList());            
    System.out.println( "Filtered even numbers : "+ evenList );
 }
}

Output:
    Filtered even numbers : [2, 4, 6, 8, 10, 12]

Example of filterig with Predicate argument:

//Importing required classes for stream
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class PredicateFilterExample
   static void main ( String args[] ){
     //Creating predicate
     Predicate<Integer> pr = i -> ( i % 2 == 0 );
     Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };

     //Filtering the even numbers from a collection
     List<Integer> evenList = 
        Arrays.asList(numbers)
        .stream()
        //passing predicate in argument
        .filter(pr)
        .collect(Collectors.toList());
               
      System.out.println( "Filtered even numbers : "+ evenList );
  }
}

Output:
    Filtered even numbers : [2, 4, 6, 8]

map() Method Example In Java 8 Stream

The stream map() method is an intermediate operation. This method transforms elements of a stream by applying a mapping function to each of the elements and returns a new stream. It accepts a Function mapper object as an argument. This function describes how each element in the original stream is transformed into an element in the new stream.

  1. Stream map(Function mapper) is an intermediate operation.
  2. Stream map() method accepts a Function mapper object in argument.
  3. Stream map() method is used to transform elements of a stream by applying a mapping function to each of the elements.
  4. Stream map() method returnes a new stream.

Syntax:

 Stream map(Function mapper)

Example of stream map method with collect method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamMapExample {
   public static void main (String args[]){ 
   Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
   //Filtering the even numbers from a collection
   List<Integer> evenList = 
   Arrays.asList(numbers).stream() 
        //passing lambda expression in argument
        .filter(i -> i % 2 == 0)
        //multiplying by 2 for each element after filter
        .map(i -> i*2)
        .collect(Collectors.toList());
               
  System.out.println("Filtered even numbers : "+ evenList);
 }
}


Output:
    Filtered even numbers : [4, 8, 12, 16, 20, 24]

Example of stream map method with forEach method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamMapExample {
  public static void main (String args[]){ 
  Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  //Filtering the even numbers from a collection
  Arrays.asList(numbers).stream()
        //passing lambda expression in argument
        .filter(i -> i % 2 == 0)
        //multiplying by 3 for each element after filter
        .map(i -> i*3)
        //forEach with method reference
        .forEach(System.out::println);    
  }
}

Output:
    6
    12
    18
    24
    30
    36

Stream sorted() Method Example In Java

Stream interface provides a sorted() method to sort a list. The sorted() method returns a sorted stream according to the natural order. If the elements are not comparable, it throws java.lang.ClassCastException.

  1. Stream sorted() method is an intermediate operation.
  2. Stream interface provides a sorted() method to sort a list.
  3. Stream sorted() method returns a sorted stream according to the natural order.
  4. If the elements are not comparable, it throws java.lang.ClassCastException.

Syntax:

 Stream<T<> sorted()

Syntax of sorted method with comparator in argument:

 Stream<T<> sorted(Comparator<? Super T> comparator)  

Example of stream sorted method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamSortedExample {
  public static void main ( String args[]){ 
    Integer[] numbers = { 100, 20, 13, 440, 5, 16, 7, 28, 2, 11, 1 };
    ListInteger> sortedList = 
    Arrays.asList(numbers).stream() 
        .sorted()
        .collect( Collectors.toList() );
                
    System.out.println( ""Sorted list : "+ sortedList ); 
  }
}


Output:
    Sorted list : [1, 2, 5, 7, 11, 13, 16, 20, 28, 100, 440]

Example of stream sorted method with forEach method

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class StreamSortedExample {
  public static void main (String args[]){
    Integer[] numbers = { 100, 20, 13, 440, 5, 16, 7, 28, 2, 11, 1 };
    List<Integer> sortedList = 
    Arrays.asList( numbers ).stream()
            .sorted()
            //forEach with method reference
            .forEach( System.out :: println );
 }
}
 
Output:
    1
    2
    5
    7
    11
    13
    16
    20
    28
    100
    440

Example of sorted method with comparator in argument:

public class Students {
    private Integer age;
    private String name;

    Students(Integer age,String name){
        this.age=age;
        this.name=name;
    }

    public String toString() {
        return this.age + ", "+ this.name;
    }
}

//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;
public class SortedExampleWithComparator {
  public static void main ( String args[]){
    List<Students> studentsList = new ArrayList<Students>();
    studentsList.add( new Students( 18, "Pankaj" ));
    studentsList.add( new Students( 20, "Prakash" ));
    studentsList.add( new Students( 16, "Karim" ));
    studentsList.add( new Students( 19, "Shyam" ));

    studentsList
    .stream()
    //comparator
    .sorted(( s1, s2 ) -> s1.age.compareTo( s2.age ))
    //forEach with method reference
    .forEach( System.out :: println );
  }             
}

Output:
    16, Karim
    18, Pankaj
    19, Shyam
    20, Prakash

forEach() Method Example In Java Stream

The forEach() method is a default method defined in the Iterable and Stream interface. It is a terminal operation in stream API. The purpose of the forEach() method is iterating the elements one by one of a collection to create a result. The forEach() method accept a single argument which is a functional interface. So, you can pass a lambda expression in argument.

  1. The forEach() method is a default method in the Iterable and Stream interface.
  2. The forEach() method is a terminal operation.
  3. The forEach() method iterates the elements one by one of a collection to produce a result.
  4. The forEach() method accept one single argument which is a functional interface.
  5. We can pass a lambda expression in argument.

Syntax:

 default void forEach(Consumer<super T>action)  

Example of forEach() method in Java 8

//Importing required classes
import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
  public static void main(String args[]){
    //Declaring List
    List<String> countryList = new ArrayList< String >();
    countryList.add( "Afghanistan" );
    countryList.add( "Albania" );
    countryList.add( "Algeria" );
    countryList.add( "Australia" );
    countryList.add( "India" );
    countryList.add( "Brazil" );
    countryList.add( "Japan" );
    countryList.add( "Italy" );

    //forEach method to printing country names
    countryList.forEach( country -> System.out.println( country ) );
   
  }
}

Output:
    Afghanistan
    Albania
    Algeria
    India
    Australia
    Brazil
    Japan
    Italy

Example of forEach() method in Java 8

//Importing required classes
import java.util.ArrayList;
import java.util.List;

public class ForEachExampleWithFilter {
  public static void main(String args[]){
    //Declaring List
    List<Integer> intList = new ArrayList< Integer >();
    intList.add( 100 );
    intList.add( 99 );
    intList.add( 78 );
    intList.add( 3 );
    intList.add( 6 );
    intList.add( 8 );
    intList.add( 50 );
    intList.add( 55 );

    //forEach method to printing even numbers
    intList.stream()
        .filter(i -> i%2==0)
        //method reference
        .forEach( System.out :: println );
  }
}

Output:
    100
    78
    6
    8
    50

Example of Java Stream forEach method:

public class Students {
    private Integer age;
    private String name;

    Students(Integer age,String name){
        this.age=age;
        this.name=name;
    }
    //toString() method for printing
    public String toString() {
        return this.age + ", "+ this.name;
    }
}


//Importing required classes
import java.util.*;
import java.io.*;
import java.util.stream.*;

public class SortedExampleWithComparator {
  public static void main (String args[]){
    List<Students> studentsList = new ArrayList< Students >();
    studentsList.add(new Students( 18, "Pankaj" ));
    studentsList.add(new Students( 20, "Prakash" ));
    studentsList.add(new Students( 16, "Karim" ));
    studentsList.add(new Students( 19, "Shyam" ));
    
    studentsList
        .stream()
        //filtering the studentsList with age greater than 15 
        .filter(s -> s.age>15)
        //forEach with method reference
        .forEach(System.out::println);   
 }   
}

Output:
    20, Prakash
    16, Karim
    19, Tejas

collect() Method Example In Java

The stream.collect() method accumulate elements of any Stream into a Collection, it is a part of stream terminal operation.
The Collector class provides different methods like toList(), toSet(), toMap(), and toConcurrentMap() to collect the result of Stream into List, Set, Map, and ConcurrentMap in Java. It accepts a Collector in arguments to accumulate elements of Stream into a specified Collection such as stream().collect( Collectors.toList() ), stream().collect( Collectors.toSet() ), stream().collect (Collectors.toMap(....) ), stream().collect( Collectors.counting()) etc..

It is used to perform different types of reduction operations such as calculating the sum of numeric values, finding the minimum or maximum number, concatenating strings to new string, collecting elements into a new stream.

  1. The stream.collect() method is a part of stream terminal operation.
  2. The stream.collect() method accumulate elements of any Stream into a Collection.
  3. It is used to convert to list using, stream().collect(Collectors.toList()).
  4. It is used to convert to map using, stream().collect(Collectors.toMap()).
  5. It is used to convert to set using, stream().collect(Collectors.toSet()).
  6. It is used for calculating the sum of numeric values.
  7. It is used for collecting elements into a new stream.
  8. It is used for concatenating strings to new string.
  9. It is used for finding the minimum or maximum number.

Syntax:

 stream.collect() 

Example With Syntax:

List<Integer> evenNumList = list.stream().filter( i-> i%2 == 0 )
        //Converting filtered data to a List using collect method
        .collect(Collectors.toList());
    

Example of collect() method for the convrting Stream to List

//Importing required classes
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.*;
    
    public class CollectMethodExample {
     public static void main(String args[]){
        //Declaring List
        List<Integer> intList = new ArrayList< Integer >();
        intList.add( 6 );
        intList.add( 11 );
        intList.add( 14 );
        intList.add( 7 );
        intList.add( 3 );
        intList.add( 2 );
        intList.add( 16 );
        intList.add( 15 );
        intList.add( 19 );
    
        List<Integer> evenNumList = 
            intList.stream()
            .filter( i-> i%2==0 )
            //Converting filtered data to a List
            .collect( Collectors.toList() );
    
        System.out.println( "Even Num List" +evenNumList )
    
      }
    }
    
    Output:
        Even Num List [6, 14, 2, 16]
    

Example of collect() method for the convrting Stream to Map

public class Students {
    Integer rollNumber;
     final String studentName;;
     Students( Integer rollNumber,String name){
       this.rollNumber=rollNumber;
       this.studentName=name;
     }
    
     public String toString() {
        return this.rollNumber + ", "+ this.studentName;
     }
    }
    
    
    //Importing required classes
    import java.util.*;
    import java.io.*;
    import java.util.stream.*;
    
    public class CollectMapExample {
      public static void main (String args[]){
      List<Students> studentsList = new ArrayList< Students >();
      studentsList.add( new Students( 1, "Pankaj" ));
      studentsList.add( new Students( 6, "Prakash" ));
      studentsList.add( new Students( 3, "Karim" ));
      studentsList.add( new Students( 2, "Shyam" ));
      studentsList.add( new Students( 4, "Tejas" ));
      studentsList.add( new Students( 5, "Rahul" ));
                   
      Map<Integer, String> studentMap =
            studentsList.stream()
            .collect(Collectors
            .toMap(
                p -> p.rollNumber, p -> p.studentName));
    
     //Printing the map
      System.out.println( "Student Map " +studentMap);
      
      }        
    }
    
    Output:
     {1=Pankaj, 2=Shyam, 3=Karim, 4=Tejas, 5=Rahul, 6=Prakash}
    

anyMatch() Method Example In Java 8

The anyMatch() method returns elements whether any match with the provided predicate. The anyMatch() method executes untill determining the result. Its terminate the loop execution when found any match and returns the value.

  1. The anyMatch method returns elements whether any match with the provided predicate.
  2. The anyMatch method executes untill determining the result.
  3. Its terminate the loop execution when found any match and returns the value.
  4. boolean result = list.stream().anyMatch(n -> n == 5); It will check whether 5 is available or not in the list.
  5. Return type Boolean, returns true if matches or returns false if does not matches.

Syntax:

 boolean anyMatch(Predicate predicate) 

Example of anyMatch() method

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class AnyMatchMethodExample {
 public static void main(String args[]){
    //Declaring List
    List<Integer> intList = new ArrayList< Integer >();
    intList.add( 6 );
    intList.add( 11 );
    intList.add( 14 );
    intList.add( 7 );
    intList.add( 3 );
    intList.add( 2 );
    intList.add( 16 );
    intList.add( 15 );
    intList.add( 19 );

    //calling anymatch method
    boolean result = intList.stream().anyMatch( n -> n==14 ); 

    System.out.println( result )

  }
}


Output:
    true

allMatch() Method Example In Java 8

The stream allMatch() method returns whether all elements of this stream match the provided predicate. Its check whether all elements are present or not in the given stream.

  1. The allMatch method returns whether all elements of this stream match the provided predicate.
  2. Its check whether all elements are present or not in the given stream.
  3. boolean result = list.stream().anyMatch(n -> n == 5); It will check whether 5 is available in the list.
  4. Return type Boolean, returns true if all elements are present

Syntax:

 boolean allMatch(Predicate predicate) 

Example of allMatch() method

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class AllMatchMethodExample {
 public static void main(String args[]){
    //Declaring List
    List<Integer> intList = new ArrayList< Integer >();
    intList.add( 6 );
    intList.add( 11 );
    intList.add( 14 );
    intList.add( 7 );
    intList.add( 3 );
    intList.add( 2 );
    intList.add( 16 );
    intList.add( 15 );
    intList.add( 19 );

    boolean result = intList.stream().anyMatch( n -> n%2 == 0 ); 

    System.out.println( result )

  }
}

Output:
    false

Example of allMatch() method

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class AllMatchMethodExample {
 public static void main(String args[]){
  //Declaring List
  List<Integer> intList = new ArrayList< Integer >();
  intList.add(6);
  intList.add(14);
  intList.add(2);
  intList.add(16);

  boolean result = intList.stream().anyMatch( n -> n%2 == 0 ); 

  System.out.println( result )

  }
}

Output:
    true

count() Method Example In Java

The stream count() method is a part of terminal operations in java stream. The count() method returns the count of elements in the stream. The return type of count() method is long. It is the reduction process, it may traverse the stream to produce a result.

  1. The count() method is a part of terminal operations in java stream.
  2. The count() method returns the count of elements in the stream.
  3. The return type of count() method is long.
  4. It is the reduction process, it may traverse the stream to produce a result.
  5. You can use like list.stream().count().

Syntax:

 long count() 

Java Stream count() example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class CountMethodExample {
 public static void main(String args[]){
  //Declaring List
  List<Integer> intList = new ArrayList< Integer >();
  intList.add( 6 );
  intList.add( 11 );
  intList.add( 14 );
  intList.add( 7 );
  intList.add( 3 );
  intList.add( 2 );
  intList.add( 16 );
  intList.add( 15 );
  intList.add( 19 );

  //calling count method
  long count = intList.stream().count();

  System.out.println( count )
  
  }
}

Output:
    9

Java Stream count() with filter example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class CountMethodExample {
 public static void main(String args[]){
  //Declaring List
  List<Integer> intList = new ArrayList< Integer >();
  intList.add( 6 );
  intList.add( 11 );
  intList.add( 14 );
  intList.add( 7 );
  intList.add( 3 );
  intList.add( 2 );
  intList.add( 16 );
  intList.add( 15 );
  intList.add( 19 );

  long count = intList.stream()
                .filter(i -> i%2==0)
                .count(); //calling count method

  System.out.println( count )
  
  }
}

Output:
    4

Stream reduce() Method Example In Java

The reduce() method is a part of terminal operations in java stream. It performs operations to produce a single value as result by reducing, such as average(), sum(), min(), max(), and count() etc. The reduce() method applies the binary operator to each of the elements to reduce it to a single value. The return type of the reduce() method is type T or it can be an Optional.

  1. We can use Stream.reduce()
  2. Syntex -> Optional<Integer> max = intList.stream().reduce(( i, j ) -> i > j ? i : j);
  3. The return type of the reduce() method is type T or it can be an Optional.
  4. The reduce method is a part of terminal operations in java stream.
  5. It performs operations to produce a single value as result by reducing, such as average(), sum(), min(), max(), and count() etc.
  6. The reduce() method applies the binary operator to each element to reduce it to a single value.

Syntax:

 Stream.reduce() 

Java Reduce Method Example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class ReduceMethodExample {
  public static void main(String args[]){
    //Declaring List
    List<Integer> intList = new ArrayList<Integer>();
    intList.add( 6 );
    intList.add( 11 );
    intList.add( 14 );
    intList.add( 7 );
    intList.add( 3 );
    intList.add( 2 );
    intList.add( 16 );
    intList.add( 15 );
    intList.add( 19 );

    Optional<Integer> max = 
            intList.stream()
            .reduce(( i, j ) -> i > j ? i : j);

    System.out.println( max )
    System.out.println( max.get() )
}
}

Output:
    Optional[19]
    19

Java Reduce Method Sum Example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class ReduceMethodExample {
  public static void main(String args[]){
    //Declaring List
    List<Integer> intList = new ArrayList<Integer>();
    intList.add( 6 );
    intList.add( 3 );
    intList.add( 2 );
    intList.add( 4 );
    intList.add( 5 );

    //sum of all elements
    int sum = intList.stream().reduce(0, 
                ( i, j ) -> i + j);

    System.out.println( sum )
  }
}

Output:
    20

Java Reduce Method IntStream range Example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class ReduceMethodExample {
  public static void main( String args[] ){
    //Multiplication of all elements with in range
    //Range will be started from 2 to 5
    //Its similar to 2*3*4*5
    iint multiplicationValue = IntStream.range(2, 6)
        .reduce(( num1, num2 ) -> num1 * num2 )
        .orElse(-1);

   System.out.println( multiplicationValue )
  }
}

Output:
    120

Java Reduce Method String Concat Example

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;

public class ReduceMethodExample {
  public static void main(String args[]){
    List<String> strList = new ArrayList<String>();
    strList.add( "One" );
    strList.add( "Two" );
    strList.add( "Three" );
    strList.add( "Four" );
    strList.add( "Five" );

    Optional<String> concatString = strList.stream()
            .reduce(( str1, str2 )
                    -> str1 + "-" + str2);

    System.out.println( concatString );
    System.out.println( concatString.get() );
  }
}

Output:
    Optional[One-Two-Three-Four-Five]
    One-Two-Three-Four-Five

Stream findFirst() Method

The findFirst() method is a part of Short circuit operation in Java Stream. It returns an Optional 1st element of the stream or empty if the stream is empty.

  1. The findFirst() method is a part of stream short circuit operation.
  2. It returns an Optional 1st element of the stream or empty if the stream is empty.
  3. Syntex is Optional<T> findFirst().

Syntax:

Optional<T> findFirst()

Example of findFirst() method of Strings in Java Stream

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class FindFirstExample {

public static void main(String args[]) {
List<String> strList = new ArrayList<String>();
strList.add("One");
strList.add("Two");
strList.add("Three");
strList.add("Four");
strList.add("Five");

Optional<String> firstElement = strList.stream().findFirst();

System.out.println(firstElement);
System.out.println(firstElement.get());
 
}
}

Output:
Optional[One]
One

Example of findFirst() method of Integers in Java Stream

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class FindFirstExample {

public static void main(String args[]) {
List<Integer> intList = new ArrayList<Integer>();
intList.add(100);
intList.add(90);
intList.add(80);
intList.add(70);
intList.add(200);

Optional<Integer> firstElement = intList.stream().findFirst();

System.out.println(firstElement);
System.out.println(firstElement.get());

}
}

Output:
Optional[100]
100

Example of findFirst() method of empty list in Java Stream

//Importing required classes
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class FindFirstExample {

public static void main(String args[]) {
List<String> strList = new ArrayList<String>();

Optional<String> firstElement = strList.stream().findFirst();

System.out.println( firstElement );
System.out.println( "Optional.get() of empty" );
System.out.println( firstElement.get() );
   
}
}

Output:
Optional.empty
Optional.get() of empty
Exception in thread "main" java.util.NoSuchElementException: No value present
at java.base/java.util.Optional.get(Optional.java:143)
at com.school.stream.FindFirstExample.main(FindFirstExample.java:21)

accept() and andThen() Method Example In Java 8

The andThen() and accept() methods are methods of Consumer Interfaces.

Consumer Interface Methods.
  1. void accept(T t)
  2. The accept() method takes as input the type T and returns no value. This is the single abstract method of Consumer. It accepts a single generic argument of type T and returns nothing (i.e. void). This is the method that's implemented by a lambda expression or method reference.
  3. andThen(Consumer after)
  4. The andThen() is a default method. In other words, it has an implementation and is thus non-abstract. The method accepts a Consumer and returns another Consumer.

Example of accept() method of Consumer Interface

import java.util.function.Consumer;

public class ConsumerInterfaceExample{
static void  welcomeGreeting (String name){
System.out.println( "Welcome "+name );
}
static void showAge (int age){
System.out.println( "Your age is "+age );
}
static void showSalary (int sal){
System.out.println( "Your salary is "+sal );
}

public static void main( String[] args) {
//method reference 
Consumer<String> consumer1 =
ConsumerInterfaceExample :: welcomeGreeting;
// Calling Consumer method
consumer1.accept( "Tejas" );

//method reference    
Consumer<Integer> consumer2 = 
ConsumerInterfaceExample::showAge;  
// Calling Consumer method
consumer2.accept( 30 );

//method reference
Consumer<Integer> consumer2 = 
ConsumerInterfaceExample :: showSalary;
// Calling Consumer method 
consumer2.accept( 20000 );
   
}
}


Output:
Welcome Tejas
Your age is 30
Your salary is 20000

Example of accept() and andThen Method Ina Java

import java.util.function.Consumer;

public class ConsumerInterfaceExample{
public static void main(String[] args) {
//method reference 
Consumer<String> consumer1 =
s -> System.out.println( "Welcome "+s );

Consumer<String> consumer2 =
s -> System.out.println( "Welcome "+s+ "to the World!" );

Consumer<String> consumer2 =
consumer1.andThen( consumer2 );

// Calling Consumer method
consumer1.accept( "Tejas" ); 

}
}


Output:
Welcome Tejas
Welcome Tejas to the World!

Predicate and() Method Example In Java

Predicate accepts an argument and returns a boolean value. Predicate functional interface in Java is a type of function that accepts a single argument and returns a boolean (True/ False). It provides the functionality of filtering, it filter a stream components on the base of a provided predicate.

Predicate Interface Methods.
  1. default Predicate and(Predicate other)
  2. The Predicate and() method is used to compose two expression(lambda) that represents a short-circuiting logical AND of this predicate. It can be uses to perform logical operations by combining two lambda expressions. See the example below. Here, we used and() method to check whether a number lies between two numeric range or not.

    Example of Predicate and method

    public static void main( String[] args) {   
      Predicate<Integer> pr1 = 
        x -> (x > 20);
    
      Predicate<Integer> pr2 = 
        x -> (x < 80);
    
      // Calling Predicate method  
      System.out.println(
        pr1.and( pr2 ).test(100)
      ); 
      // Calling Predicate method  
      System.out.println(
        pr1.and( pr2 ).test(50)
      ); 
      // Calling Predicate method  
      System.out.println(
        pr1.and( pr2 ).test(10)
      );
    }
    
    Output:
        false
        true
        false
    

  3. static Predicate isEqual(Object targetRef)
  4. The Predicate isEqual() method is a static method of the Predicate interface that is used to test the equality of two objects. The object can be a string, integer, or a class object.

    Example of Predicate isEqual method

    public static void mai( String[] args) {  
      Predicate<String> pr = 
            Predicate.isEqual( "MyAllText" );
      
      // Calling Predicate method  
      System.out.println(
        pr.test( "AllText" )
      ); 
      // Calling Predicate method  
      System.out.println(
        pr.test( "MyAllText" )
      );
      // Calling Predicate method  
      System.out.println(
        pr.test( "MyAll" )
      );        
    }
    
    Output:
        false
        true
        false
    

  5. default Predicate negate()
  6. The Predicate negate() method allows invert the result of a Predicate. It returns a predicate that represents the logical negation of this predicate.

    Example of Predicate negate method

    public static void main( String[] args) {
      Predicate<String> startsWithCharJ = 
        s -> s.startsWith( "H" );
      Predicate<String> hasLengthOfInt5 = 
        s -> s.length() == 5;
    
        // Calling without negate method 
        System.out.println(
          startsWithCharJ.test( "Horse" )
        ); 
        // Calling without negate method 
        System.out.println(
          hasLengthOfInt5.test( "India" )
        ); 
    
      Predicate<String> negateStartsWithCharJ = 
        startsWithCharJ.negate();
      Predicate<String> negatehasLengthOfInt5 = 
        hasLengthOfInt5.negate();
    
        // Calling after negate predicate 
        System.out.println(
           negateStartsWithCharJ.test( "Horse" )
        ); 
        // Calling after negate predicate 
        System.out.println(
          negatehasLengthOfInt5.test( "India" )
        );     
    } 
    
    Output:
        true
        true
        false
        false
    
    

  7. or(Predicate other)
  8. The Predicate or() method works similarly to and(), but it returns true if either of the any Predicates return true.

    Example of Predicate or method

    public static void main( String[] args) { 
      Predicate<String> startsWithCharH = 
        s -> s.startsWith( "H" );
      Predicate<String> hasLengthOfInt5 = 
        s -> s.length() == 5;
    
      Predicate<String> startsWithCharHOrHasLengthOf5 = 
        startsWithCharH.or( hasLengthOfInt5 );
    
        System.out.println( 
            startsWithCharHOrHasLengthOf5
            .test( "Hero" )
        ); 
        System.out.println(
            startsWithCharHOrHasLengthOf5
            .test( "India" )
        ); 
        System.out.println(
            startsWithCharHOrHasLengthOf5
            .test( "Method" )
        );
    } 
    
    Output:
        true
        true
        false
    

  9. boolean test(T t)
  10. The Predicate test() method returns true if the input argument matches the predicate, otherwise false.

    Example of Predicate test method

    public static void main( String[] args){ 
      Predicate<Integer> pr = a -> ( a > 10 );
    
      // Calling Predicate method  
      System.out.println( pr.test(20) );       
    } 
    
    Output:
        true
    

Predicate isEqual() Method Example In Java

Predicate accepts an argument and returns a boolean value. Predicate functional interface in Java is a type of function that accepts a single argument and returns a boolean (True/ False). It provides the functionality of filtering, it filter a stream components on the base of a provided predicate.

Predicate Interface Methods.
  1. static Predicate isEqual(Object targetRef)
  2. The Predicate isEqual() method is a static method of the Predicate interface that is used to test the equality of two objects. The object can be a string, integer, or a class object.

    Example of Predicate isEqual method

    public static void mai( String[] args) {  
    Predicate<String> pr = 
        Predicate.isEqual( "MyAllText" );
    
    // Calling Predicate method  
    System.out.println(
    pr.test( "AllText" )
    ); 
    // Calling Predicate method  
    System.out.println(
    pr.test( "MyAllText" )
    );
    // Calling Predicate method  
    System.out.println(
    pr.test( "MyAll" )
    );        
    }
    
    Output:
    false
    true
    false
    

  3. default Predicate negate()
  4. The Predicate negate() method allows invert the result of a Predicate. It returns a predicate that represents the logical negation of this predicate.

    Example of Predicate negate method

    public static void main( String[] args) {
    Predicate<String> startsWithCharJ = 
    s -> s.startsWith( "H" );
    Predicate<String> hasLengthOfInt5 = 
    s -> s.length() == 5;
    
    // Calling without negate method 
    System.out.println(
      startsWithCharJ.test( "Horse" )
    ); 
    // Calling without negate method 
    System.out.println(
      hasLengthOfInt5.test( "India" )
    ); 
    
    Predicate<String> negateStartsWithCharJ = 
    startsWithCharJ.negate();
    Predicate<String> negatehasLengthOfInt5 = 
    hasLengthOfInt5.negate();
    
    // Calling after negate predicate 
    System.out.println(
       negateStartsWithCharJ.test( "Horse" )
    ); 
    // Calling after negate predicate 
    System.out.println(
      negatehasLengthOfInt5.test( "India" )
    );     
    } 
    
    Output:
    true
    true
    false
    false
    
    

  5. or(Predicate other)
  6. The Predicate or() method works similarly to and(), but it returns true if either of the any Predicates return true.

    Example of Predicate or method

    public static void main( String[] args) { 
    Predicate<String> startsWithCharH = 
    s -> s.startsWith( "H" );
    Predicate<String> hasLengthOfInt5 = 
    s -> s.length() == 5;
    
    Predicate<String> startsWithCharHOrHasLengthOf5 = 
    startsWithCharH.or( hasLengthOfInt5 );
    
    System.out.println( 
        startsWithCharHOrHasLengthOf5
        .test( "Hero" )
    ); 
    System.out.println(
        startsWithCharHOrHasLengthOf5
        .test( "India" )
    ); 
    System.out.println(
        startsWithCharHOrHasLengthOf5
        .test( "Method" )
    );
    } 
    
    Output:
    true
    true
    false
    

  7. boolean test(T t)
  8. The Predicate test() method returns true if the input argument matches the predicate, otherwise false.

    Example of Predicate test method

    public static void main( String[] args){ 
    Predicate<Integer> pr = a -> ( a > 10 );
    
    // Calling Predicate method  
    System.out.println( pr.test(20) );       
    } 
    
    Output:
    true
    

  9. default Predicate and(Predicate other)
  10. The Predicate and() method is used to compose two expression(lambda) that represents a short-circuiting logical AND of this predicate. It can be uses to perform logical operations by combining two lambda expressions. See the example below. Here, we used and() method to check whether a number lies between two numeric range or not.

    Example of Predicate and method

    public static void main( String[] args) {   
    Predicate<Integer> pr1 = 
    x -> (x > 20);
    
    Predicate<Integer> pr2 = 
    x -> (x < 80);
    
    // Calling Predicate method  
    System.out.println(
    pr1.and( pr2 ).test(100)
    ); 
    // Calling Predicate method  
    System.out.println(
    pr1.and( pr2 ).test(50)
    ); 
    // Calling Predicate method  
    System.out.println(
    pr1.and( pr2 ).test(10)
    );
    }
    
    Output:
    false
    true
    false
    

Predicate negate() Method Example In Java

Predicate accepts an argument and returns a boolean value. Predicate functional interface in Java is a type of function that accepts a single argument and returns a boolean (True/ False). It provides the functionality of filtering, it filter a stream components on the base of a provided predicate.

Predicate Interface Methods.
  1. default Predicate negate()
  2. The Predicate negate() method allows invert the result of a Predicate. It returns a predicate that represents the logical negation of this predicate.

    Example of Predicate negate method

    public static void main( String[] args) {
      Predicate<String> startsWithCharJ = 
        s -> s.startsWith( "H" );
      Predicate<String> hasLengthOfInt5 = 
        s -> s.length() == 5;
    
        // Calling without negate method 
        System.out.println(
          startsWithCharJ.test( "Horse" )
        ); 
        // Calling without negate method 
        System.out.println(
          hasLengthOfInt5.test( "India" )
        ); 
    
      Predicate<String> negateStartsWithCharJ = 
        startsWithCharJ.negate();
      Predicate<String> negatehasLengthOfInt5 = 
        hasLengthOfInt5.negate();
    
        // Calling after negate predicate 
        System.out.println(
           negateStartsWithCharJ.test( "Horse" )
        ); 
        // Calling after negate predicate 
        System.out.println(
          negatehasLengthOfInt5.test( "India" )
        );     
    } 
    
    Output:
        true
        true
        false
        false
    
    

  3. or(Predicate other)
  4. The Predicate or() method works similarly to and(), but it returns true if either of the any Predicates return true.

    Example of Predicate or method

    public static void main( String[] args) { 
      Predicate<String> startsWithCharH = 
        s -> s.startsWith( "H" );
      Predicate<String> hasLengthOfInt5 = 
        s -> s.length() == 5;
    
      Predicate<String> startsWithCharHOrHasLengthOf5 = 
        startsWithCharH.or( hasLengthOfInt5 );
    
        System.out.println( 
            startsWithCharHOrHasLengthOf5
            .test( "Hero" )
        ); 
        System.out.println(
            startsWithCharHOrHasLengthOf5
            .test( "India" )
        ); 
        System.out.println(
            startsWithCharHOrHasLengthOf5
            .test( "Method" )
        );
    } 
    
    Output:
        true
        true
        false
    

  5. boolean test(T t)
  6. The Predicate test() method returns true if the input argument matches the predicate, otherwise false.

    Example of Predicate test method

    public static void main( String[] args){ 
      Predicate<Integer> pr = a -> ( a > 10 );
    
      // Calling Predicate method  
      System.out.println( pr.test(20) );       
    } 
    
    Output:
        true
    

  7. static Predicate isEqual(Object targetRef)
  8. The Predicate isEqual() method is a static method of the Predicate interface that is used to test the equality of two objects. The object can be a string, integer, or a class object.

    Example of Predicate isEqual method

    public static void mai( String[] args) {  
      Predicate<String> pr = 
            Predicate.isEqual( "MyAllText" );
      
      // Calling Predicate method  
      System.out.println(
        pr.test( "AllText" )
      ); 
      // Calling Predicate method  
      System.out.println(
        pr.test( "MyAllText" )
      );
      // Calling Predicate method  
      System.out.println(
        pr.test( "MyAll" )
      );        
    }
    
    Output:
        false
        true
        false
    

  9. default Predicate and(Predicate other)
  10. The Predicate and() method is used to compose two expression(lambda) that represents a short-circuiting logical AND of this predicate. It can be uses to perform logical operations by combining two lambda expressions. See the example below. Here, we used and() method to check whether a number lies between two numeric range or not.

    Example of Predicate and method

    public static void main( String[] args) {   
      Predicate<Integer> pr1 = 
        x -> (x > 20);
    
      Predicate<Integer> pr2 = 
        x -> (x < 80);
    
      // Calling Predicate method  
      System.out.println(
        pr1.and( pr2 ).test(100)
      ); 
      // Calling Predicate method  
      System.out.println(
        pr1.and( pr2 ).test(50)
      ); 
      // Calling Predicate method  
      System.out.println(
        pr1.and( pr2 ).test(10)
      );
    }
    
    Output:
        false
        true
        false
    

Predicate or() Method Example In Java

Predicate accepts an argument and returns a boolean value. Predicate functional interface in Java is a type of function that accepts a single argument and returns a boolean (True/ False). It provides the functionality of filtering, it filter a stream components on the base of a provided predicate.

Predicate Interface Methods.
  1. or(Predicate other)
  2. The Predicate or() method works similarly to and(), but it returns true if either of the any Predicates return true.

    Example of Predicate or method

    public static void main( String[] args) { 
          Predicate<String> startsWithCharH = 
            s -> s.startsWith( "H" );
          Predicate<String> hasLengthOfInt5 = 
            s -> s.length() == 5;
        
          Predicate<String> startsWithCharHOrHasLengthOf5 = 
            startsWithCharH.or( hasLengthOfInt5 );
        
            System.out.println( 
                startsWithCharHOrHasLengthOf5
                .test( "Hero" )
            ); 
            System.out.println(
                startsWithCharHOrHasLengthOf5
                .test( "India" )
            ); 
            System.out.println(
                startsWithCharHOrHasLengthOf5
                .test( "Method" )
            );
        } 
        
        Output:
            true
            true
            false
        

  3. boolean test(T t)
  4. The Predicate test() method returns true if the input argument matches the predicate, otherwise false.

    Example of Predicate test method

    public static void main( String[] args){ 
          Predicate<Integer> pr = a -> ( a > 10 );
        
          // Calling Predicate method  
          System.out.println( pr.test(20) );       
        } 
        
        Output:
            true
        

  5. static Predicate isEqual(Object targetRef)
  6. The Predicate isEqual() method is a static method of the Predicate interface that is used to test the equality of two objects. The object can be a string, integer, or a class object.

    Example of Predicate isEqual method

    public static void mai( String[] args) {  
          Predicate<String> pr = 
                Predicate.isEqual( "MyAllText" );
          
          // Calling Predicate method  
          System.out.println(
            pr.test( "AllText" )
          ); 
          // Calling Predicate method  
          System.out.println(
            pr.test( "MyAllText" )
          );
          // Calling Predicate method  
          System.out.println(
            pr.test( "MyAll" )
          );        
        }
        
        Output:
            false
            true
            false
        

  7. default Predicate and(Predicate other)
  8. The Predicate and() method is used to compose two expression(lambda) that represents a short-circuiting logical AND of this predicate. It can be uses to perform logical operations by combining two lambda expressions. See the example below. Here, we used and() method to check whether a number lies between two numeric range or not.

    Example of Predicate and method

    public static void main( String[] args) {   
          Predicate<Integer> pr1 = 
            x -> (x > 20);
        
          Predicate<Integer> pr2 = 
            x -> (x < 80);
        
          // Calling Predicate method  
          System.out.println(
            pr1.and( pr2 ).test(100)
          ); 
          // Calling Predicate method  
          System.out.println(
            pr1.and( pr2 ).test(50)
          ); 
          // Calling Predicate method  
          System.out.println(
            pr1.and( pr2 ).test(10)
          );
        }
        
        Output:
            false
            true
            false
        

  9. default Predicate negate()
  10. The Predicate negate() method allows invert the result of a Predicate. It returns a predicate that represents the logical negation of this predicate.

    Example of Predicate negate method

    public static void main( String[] args) {
          Predicate<String> startsWithCharJ = 
            s -> s.startsWith( "H" );
          Predicate<String> hasLengthOfInt5 = 
            s -> s.length() == 5;
        
            // Calling without negate method 
            System.out.println(
              startsWithCharJ.test( "Horse" )
            ); 
            // Calling without negate method 
            System.out.println(
              hasLengthOfInt5.test( "India" )
            ); 
        
          Predicate<String> negateStartsWithCharJ = 
            startsWithCharJ.negate();
          Predicate<String> negatehasLengthOfInt5 = 
            hasLengthOfInt5.negate();
        
            // Calling after negate predicate 
            System.out.println(
               negateStartsWithCharJ.test( "Horse" )
            ); 
            // Calling after negate predicate 
            System.out.println(
              negatehasLengthOfInt5.test( "India" )
            );     
        } 
        
        Output:
            true
            true
            false
            false
        
        

Predicate test() Method Example In Java

Predicate accepts an argument and returns a boolean value. Predicate functional interface in Java is a type of function that accepts a single argument and returns a boolean (True/ False). It provides the functionality of filtering, it filter a stream components on the base of a provided predicate.

Predicate Interface Methods.
  1. boolean test(T t)
  2. The Predicate test() method returns true if the input argument matches the predicate, otherwise false.

    Example of Predicate test method

    public static void main( String[] args){ 
          Predicate<Integer> pr = a -> ( a > 10 );
        
          // Calling Predicate method  
          System.out.println( pr.test(20) );       
        } 
        
        Output:
            true
        

  3. static Predicate isEqual(Object targetRef)
  4. The Predicate isEqual() method is a static method of the Predicate interface that is used to test the equality of two objects. The object can be a string, integer, or a class object.

    Example of Predicate isEqual method

    public static void mai( String[] args) {  
          Predicate<String> pr = 
                Predicate.isEqual( "MyAllText" );
          
          // Calling Predicate method  
          System.out.println(
            pr.test( "AllText" )
          ); 
          // Calling Predicate method  
          System.out.println(
            pr.test( "MyAllText" )
          );
          // Calling Predicate method  
          System.out.println(
            pr.test( "MyAll" )
          );        
        }
        
        Output:
            false
            true
            false
        

  5. default Predicate and(Predicate other)
  6. The Predicate and() method is used to compose two expression(lambda) that represents a short-circuiting logical AND of this predicate. It can be uses to perform logical operations by combining two lambda expressions. See the example below. Here, we used and() method to check whether a number lies between two numeric range or not.

    Example of Predicate and method

    public static void main( String[] args) {   
          Predicate<Integer> pr1 = 
            x -> (x > 20);
        
          Predicate<Integer> pr2 = 
            x -> (x < 80);
        
          // Calling Predicate method  
          System.out.println(
            pr1.and( pr2 ).test(100)
          ); 
          // Calling Predicate method  
          System.out.println(
            pr1.and( pr2 ).test(50)
          ); 
          // Calling Predicate method  
          System.out.println(
            pr1.and( pr2 ).test(10)
          );
        }
        
        Output:
            false
            true
            false
        

  7. default Predicate negate()
  8. The Predicate negate() method allows invert the result of a Predicate. It returns a predicate that represents the logical negation of this predicate.

    Example of Predicate negate method

    public static void main( String[] args) {
          Predicate<String> startsWithCharJ = 
            s -> s.startsWith( "H" );
          Predicate<String> hasLengthOfInt5 = 
            s -> s.length() == 5;
            System.out.println("**Before Negating**")
            // Calling without negate method 
            System.out.println(
              startsWithCharJ.test( "Horse" )
            ); 
            // Calling without negate method 
            System.out.println(
              hasLengthOfInt5.test( "India" )
            ); 
        
          // Here we are negating 
          Predicate<String> negateStartsWithCharJ = 
            startsWithCharJ.negate();
          Predicate<String> negatehasLengthOfInt5 = 
            hasLengthOfInt5.negate();
        
            System.out.println("**After Negating**")
           
            // Calling after negate predicate 
            System.out.println(
               negateStartsWithCharJ.test( "Horse" )
            ); 
            // Calling after negate predicate 
            System.out.println(
              negatehasLengthOfInt5.test( "India" )
            );     
        } 
        
        Output:
            **Before Negating**
            true
            true
            **After Negating**
            false
            false
        
        

  9. or(Predicate other)
  10. The Predicate or() method works similarly to and(), but it returns true if either of the any Predicates return true.

    Example of Predicate or method

    public static void main( String[] args) { 
          Predicate<String> startsWithCharH = 
            s -> s.startsWith( "H" );
          Predicate<String> hasLengthOfInt5 = 
            s -> s.length() == 5;
        
          Predicate<String> startsWithCharHOrHasLengthOf5 = 
            startsWithCharH.or( hasLengthOfInt5 );
        
            System.out.println( 
                startsWithCharHOrHasLengthOf5
                .test( "Hero" )
            ); 
            System.out.println(
                startsWithCharHOrHasLengthOf5
                .test( "India" )
            ); 
            System.out.println(
                startsWithCharHOrHasLengthOf5
                .test( "Method" )
            );
        } 
        
        Output:
            true
            true
            false