Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Function Interface in Java
Next article icon

Java 8 Predicate with Examples

Last Updated : 21 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

A Functional Interface is an Interface which allows only one Abstract method within the Interface scope. There are some predefined functional interface in Java like Predicate, consumer, supplier etc. The return type of a Lambda function (introduced in JDK 1.8) is a also functional interface.

The Functional Interface PREDICATE is defined in the java.util.function package. It improves manageability of code, helps in unit-testing them separately, and contain some methods like:

  1. isEqual(Object targetRef) : Returns a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).
    static  Predicate isEqual(Object targetRef)  Returns a predicate that tests if two arguments are   equal according to Objects.equals(Object, Object).  T : the type of arguments to the predicate  Parameters:  targetRef : the object reference with which to   compare for equality, which may be null  Returns: a predicate that tests if two arguments   are equal according to Objects.equals(Object, Object)  
  2. and(Predicate other) : Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
    default Predicate and(Predicate other)  Returns a composed predicate that represents a   short-circuiting logical AND of this predicate and another.  Parameters:  other: a predicate that will be logically-ANDed with this predicate  Returns : a composed predicate that represents the short-circuiting   logical AND of this predicate and the other predicate  Throws: NullPointerException - if other is null
  3. negate() : Returns a predicate that represents the logical negation of this predicate.
    default Predicate negate()  Returns:a predicate that represents the logical   negation of this predicate
  4. or(Predicate other) : Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.
    default Predicate or(Predicate other)  Parameters:  other : a predicate that will be logically-ORed with this predicate  Returns:  a composed predicate that represents the short-circuiting   logical OR of this predicate and the other predicate  Throws : NullPointerException - if other is null
  5. test(T t) : Evaluates this predicate on the given argument.boolean test(T t)
    test(T t)   Parameters:  t - the input argument  Returns:  true if the input argument matches the predicate, otherwise false

Examples

Example 1: Simple Predicate

Java




// Java program to illustrate Simple Predicate
  
import java.util.function.Predicate;
public class PredicateInterfaceExample1 {
    public static void main(String[] args)
    {
        // Creating predicate
        Predicate<Integer> lesserthan = i -> (i < 18); 
  
        // Calling Predicate method
        System.out.println(lesserthan.test(10)); 
    }
}
 
 


Output:
  True  

Example 2: Predicate Chaining

Java




// Java program to illustrate Predicate Chaining
  
import java.util.function.Predicate;
public class PredicateInterfaceExample2 {
    public static void main(String[] args)
    {
        Predicate<Integer> greaterThanTen = (i) -> i > 10;
  
        // Creating predicate
        Predicate<Integer> lowerThanTwenty = (i) -> i < 20; 
        boolean result = greaterThanTen.and(lowerThanTwenty).test(15);
        System.out.println(result);
  
        // Calling Predicate method
        boolean result2 = greaterThanTen.and(lowerThanTwenty).negate().test(15);
        System.out.println(result2);
    }
}
 
 


Output:
  True  False  

Example 3: Predicate in to Function

Java




// Java program to illustrate 
// passing Predicate into function
  
import java.util.function.Predicate;
class PredicateInterfaceExample3 {
    static void pred(int number, Predicate<Integer> predicate)
    {
        if (predicate.test(number)) {
            System.out.println("Number " + number);
        }
    }
    public static void main(String[] args)
    {
        pred(10, (i) -> i > 7);
    }
}
 
 


Output:
  Number 10  

Example 4: Predicate OR

Java




// Java program to illustrate OR Predicate
  
import java.util.function.Predicate;
class PredicateInterfaceExample4 {
    public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_or()
    {
  
        Predicate<String> containsLetterA = p -> p.contains("A");
        String containsA = "And";
        boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);
        System.out.println(outcome);
    }
    public static void main(String[] args)
    {
        predicate_or();
    }
}
 
 


Output:
  True  

Example 5: Predicate AND

Java




// Java program to illustrate AND Predicate
  
import java.util.function.Predicate;
import java.util.Objects;
  
class PredicateInterfaceExample5 {
    public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_and()
    {
        Predicate<String> nonNullPredicate = Objects::nonNull;
  
        String nullString = null;
  
        boolean outcome = nonNullPredicate.and(hasLengthOf10).test(nullString);
        System.out.println(outcome);
  
        String lengthGTThan10 = "Welcome to the machine";
        boolean outcome2 = nonNullPredicate.and(hasLengthOf10).
        test(lengthGTThan10);
        System.out.println(outcome2);
    }
    public static void main(String[] args)
    {
        predicate_and();
    }
}
 
 


Output:
  False  True  

Example 6: Predicate negate()

Java




// Java program to illustrate 
// negate Predicate
  
import java.util.function.Predicate;
class PredicateInterfaceExample6 {
    public static Predicate<String> hasLengthOf10 = new Predicate<String>() {
        @Override
        public boolean test(String t)
        {
            return t.length() > 10;
        }
    };
  
    public static void predicate_negate()
    {
  
        String lengthGTThan10 = "Thunderstruck is a 2012 children's "
                                + "film starring Kevin Durant";
  
        boolean outcome = hasLengthOf10.negate().test(lengthGTThan10);
        System.out.println(outcome);
    }
    public static void main(String[] args)
    {
        predicate_negate();
    }
}
 
 


Output:
  False  

Example 7: Predicate in Collection

Java




// Java program to demonstrate working of predicates
// on collection. The program finds all admins in an
// arrayList of users.
import java.util.function.Predicate;
import java.util.*;
class User
{
    String name, role;
    User(String a, String b) {
        name = a;
        role = b;
    }
    String getRole() { return role; }
    String getName() { return name; }    
    public String toString() {
       return "User Name : " + name + ", Role :" + role;
    }
  
    public static void main(String args[])
    {      
        List<User> users = new ArrayList<User>();
        users.add(new User("John", "admin"));
        users.add(new User("Peter", "member"));
        List admins = process(users, (User u) -> u.getRole().equals("admin"));
        System.out.println(admins);
    }
  
    public static List<User> process(List<User> users, 
                            Predicate<User> predicate)
    {
        List<User> result = new ArrayList<User>();
        for (User user: users)        
            if (predicate.test(user))            
                result.add(user);
        return result;
    }
}
 
 


Output:
[User Name : John, Role :admin]  

The same functionality can also be achieved by using Stream API
and lambda functions offered since JDK 1.8 on top of the Collections API.

The Stream API allows "streaming" of collections for dynamic processing. Streams allow concurrent and parallel computation on data (using internal iterations), to support database-like operations such as grouping and filtering the data (similar to GROUP BY and WHERE clause in SQL). This allows the developers to focus on "what data is needed" instead of "how data is needed" since streaming hides the details of the implementation and provides the result. This is done by providing predicates as inputs to functions operating at runtime upon the streams of collections. In the following example, we illustrate how Stream API can be used along with predicates to filter the collections of data as achieved in Example 7.

Java




// Java program to demonstrate working of predicates
// on collection. The program finds all admins in an
// arrayList of users.
import java.util.function.Predicate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
class User
{
    String name, role;
    User(String a, String b) {
        name = a;
        role = b;
    }
    String getRole() { return role; }
    String getName() { return name; } 
    public String toString() {
    return "User Name : " + name + ",
    Role :" + role;
    }
  
    public static void main(String args[])
    { 
        List<User> users = 
            new ArrayList<User>();
        users.add(new User("John", "admin"));
        users.add(new User("Peter", "member"));
          
    // This line uses Predicates to filter
    // out the list of users with the role "admin".
    // List admins = process(users, (User u) -> 
    // u.getRole().equals("admin"));
  
    // Replacing it with the following line 
    // using Stream API and lambda functions 
    // produces the same output
      
    // the input to the filter() is a lambda 
    // expression that returns a predicate: a 
    // boolean value for each user encountered 
    // (true if admin, false otherwise)
    List admins = users.stream()
    .filter((user) -> user.getRole().equals("admin"))
    .collect(Collectors.toList());
          
    System.out.println(admins);
    }
}
 
 

Output:

[User Name : John, Role :admin]  


Next Article
Function Interface in Java

A

ashish sinha 7
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Java 8 Features - Complete Tutorial
    Java 8 is the most awaited release of the Java programming language development because, in the entire history of Java, it has never released that many major features. It consists of major features of Java. It is a new version of Java and was released by Oracle on 18 March 2014. Java provided suppor
    9 min read
  • Lambda Expressions

    • Java Lambda Expressions
      Lambda expressions in Java, introduced in Java SE 8. It represents the instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code. Key Functionalities of Lambda ExpressionLambda Expr
      6 min read

    • Java - Lambda Expressions Parameters
      Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions express instances of functional interfaces An interface with a single abstract method is called a functional interface. One example is java
      5 min read

    • Java Lambda Expression with Collections
      In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: - compare().
      3 min read

    • Java - Lambda Expression Variable Capturing with Examples
      Variable defined by the enclosing scope of a lambda expression are accessible within the lambda expression. For example, a lambda expression can use an instance or static variable defined by its enclosing class. A lambda expression also has access to (both explicitly and implicitly), which refers to
      4 min read

    • How to Create Thread using Lambda Expressions in Java?
      Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here. Syntax: (argument1, argument2, .. argument n) -> { // statements }; Her
      3 min read

    • Serialization of Lambda Expression in Java
      Here we will be discussing serialization in java and the problems related to the lambda function without the serialization alongside discussing some ways due to which we require serialization alongside proper implementation as in clean java programs with complete serialization and deserialization pr
      5 min read

    • Block Lambda Expressions in Java
      Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda's body consists of a block of code. If it has only a single expression they are called "Expression Bodies". Lambdas which contain expr
      4 min read

    • Match Lambdas to Interfaces in Java
      One of the most popular and important topics is lambda expression in java but before going straight into our discussion, let us have insight into some important things. Starting off with the interfaces in java as interfaces are the reference types that are similar to classes but containing only abst
      5 min read

    • Converting ArrayList to HashMap in Java 8 using a Lambda Expression
      A lambda expression is one or more line of code which works like function or method. It takes a parameter and returns the value. Lambda expression can be used to convert ArrayList to HashMap. Syntax: (parms1, parms2) -> expressionExamples: Input : List : [1="1", 2="2", 3="3"] Output: Map : {1=1,
      2 min read

    • Check if a String Contains Only Alphabets in Java Using Lambda Expression
      Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String
      3 min read

    • Remove elements from a List that satisfy given predicate in Java
      Below are the methods to efficiently remove elements from a List satisfying a Predicate condition: p ==> Predicate, specifying the condition l ==> List, from which element to be removed Using iterator Below program demonstrates the removal of null elements from the list, using the Predicate Ja
      5 min read

    Functional Interfaces

    • Java Functional Interfaces
      A functional interface in Java is an interface that contains only one abstract method. Functional interfaces can have multiple default or static methods, but only one abstract method. Runnable, ActionListener, and Comparator are common examples of Java functional interfaces. From Java 8 onwards, lam
      7 min read

    • Java 8 | Consumer Interface in Java with Examples
      The Consumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result. However these kind of functions don't return any value.Hence this functi
      4 min read

    • Java 8 | BiConsumer Interface in Java with Examples
      The BiConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function that takes in two arguments and produces a result. However, these kinds of functions doesn't return any value. This funct
      5 min read

    • Java 8 Predicate with Examples
      A Functional Interface is an Interface which allows only one Abstract method within the Interface scope. There are some predefined functional interface in Java like Predicate, consumer, supplier etc. The return type of a Lambda function (introduced in JDK 1.8) is a also functional interface. The Fun
      6 min read

    • Function Interface in Java
      The Function Interface is a part of the java.util.function package that has been introduced since Java 8, to implement functional programming in Java. It represents a function that takes in one argument and produces a result. Hence, this functional interface takes in 2 generics, namely as follows: T
      7 min read

    • Supplier Interface in Java with Examples
      The Supplier Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which does not take in any argument but produces a value of type T. Hence this functional interface takes in only one gener
      1 min read

    Method Reference

    • Java Method References
      As we all know a Method is a collection of statements that perform some specific task and return the result to the caller. A method reference in Java is the shorthand syntax for a lambda expression that contains just one method call. In general, one doesn't have to pass arguments to method reference
      7 min read

    • Converting ArrayList to HashMap using Method Reference in Java 8
      Data Structures are a boon to everyone who codes. But is there any way to convert a Data Structure into another? Well, it seems that there is! In this article, we will be learning how to convert an ArrayList to HashMap using method reference in Java 8. Example: Elements in ArrayList are : [Pen, Penc
      2 min read

    Streams

    • Java 8 Stream Tutorial
      Java 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
      15+ min read

    • Difference Between Streams and Collections in Java
      Collection is an in-memory data structure, which holds all the values that the data structure currently has. Every element in the Collection has to be computed before we add it to the Collection. Operations such as searching, sorting, insertion, manipulation, and deletion can be performed on a Colle
      3 min read

    • Implement Filter Function using Reduce in Java 8 Streams
      Many times, we need to perform operations where a stream reduces to a single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argumen
      2 min read

    • Java Stream API – Filters
      In this article, we will learn Java Stream Filter API. We will cover, 1. How stream filter API works. 2. Filter by Object Properties. 3. Filter by Index. 4. Filter by custom Object properties. Stream Filter API Filter API takes a Predicate. The predicate is a Functional Interface. It takes an argume
      5 min read

    • Parallel vs Sequential Stream in Java
      Prerequisite: Streams in Java A stream in Java is a sequence of objects which operates on a data source such as an array or a collection and supports various methods. It was introduced in Java 8's java.util.stream package. Stream supports many aggregate operations like filter, map, limit, reduce, fi
      5 min read

    • Functional Programming in Java 8+ using the Stream API with Example
      API is an acronym for Application Programming Interface, which is software and the java streams work on a data source. Consider a stream like a flow of water in a small canal. Let's take a real-life example. Each time a user uses an application that is popular these days like WhatsApp in order to co
      4 min read

    • Intermediate Methods of Stream in Java
      The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The method provided by the stream are broadly categorized as Intermediate MethodsTerminal Methods Here, we will be discussin
      6 min read

    • Difference Between map() And flatMap() In Java Stream
      In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output. Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value,
      3 min read

    • Array to Stream in Java
      Prerequisite : Stream In Java Using Arrays.stream() : Syntax : public static <T> Stream<T> getStream(T[] arr) { return Arrays.stream(arr); } where, T represents generic type. Example 1 : Arrays.stream() to convert string array to stream. // Java code for converting string array // to str
      3 min read

    • 10 Ways to Create a Stream in Java
      The Stream API, introduced in Java 8, it is used to process collections of objects. Stream is a sequence of objects, that supports many different methods which can be pipe lined to produce the desired result. The features of Java stream are – A stream is not a data structure alternatively it takes i
      9 min read

    Java Stream Programs

    • Program to convert a Map to a Stream in Java
      A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are various method to convert Map to Stream in Java: Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which return
      4 min read

    • Program to convert Boxed Array to Stream in Java
      An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case
      3 min read

    • Program to convert Primitive Array to Stream in Java
      An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case
      3 min read

    • Program to convert a Set to Stream in Java using Generics
      Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
      3 min read

    • Program to Convert List to Stream in Java
      The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack class
      3 min read

    • Program to Convert Stream to an Array in Java
      A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired result. An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition
      3 min read

    • How to get Slice of a Stream in Java
      A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Slice of a Stream means a stream of elements that exists in a specified limit, from the original stream. Examples: Input: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Output: [15, 16, 17
      6 min read

    • Flattening Nested Collections in Java
      A stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result. Stream is used to compute elements as per the pipelined methods without altering the original value of the object. And, flattening means merging two or more collections into one. Cons
      4 min read

    • How to convert a Stream into a Map in Java
      Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. In this article, the methods to convert a stream into a map is discussed. Method 1: Using Collectors.t
      6 min read

    • Find the first element of a Stream in Java
      Given a stream containing some elements, the task is to get the first element of the Stream in Java. Example: Input: Stream = {"Geek_First", "Geek_2", "Geek_3", "Geek_4", "Geek_Last"} Output: Geek_First Input: Stream = {1, 2, 3, 4, 5, 6, 7} Output: 1 There are many methods to the find first elements
      3 min read

    Java Stream Methods

    • Stream forEach() method in Java with examples
      Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer<? super T> action) Where, Consumer is a functional int
      2 min read

    • Stream forEachOrdered() method in Java with examples
      Stream forEachOrdered(Consumer action) performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. Stream forEachOrdered(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-ef
      2 min read

    • foreach() loop vs Stream foreach() vs Parallel Stream foreach()
      foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing e
      4 min read

    • Stream of() method in Java
      Stream of(T t) Stream of(T t) returns a sequential Stream containing a single element. Syntax : static Stream of(T t) Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single spec
      2 min read

    • Java Stream findAny() with examples
      Stream findAny() returns an Optional (a container object which may or may not contain a non-null value) describing some element of the stream, or an empty Optional if the stream is empty. Syntax of findAny()Optional<T> findAny() Parameters1. Optional is a container object which may or may not
      4 min read

    • Stream anyMatch() in Java with examples
      Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, wh
      2 min read

    • Stream allMatch() in Java with examples
      Stream allMatch(Predicate predicate) returns whether all elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, wh
      3 min read

    • Stream filter() in Java with examples
      Stream filter(Predicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but ins
      3 min read

    • Stream sorted (Comparator comparator) method in Java
      Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may inco
      3 min read

    • Stream sorted() in Java
      Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously s
      2 min read

    Comparable and Comparator

    • Java Comparable vs Comparator
      In Java, both Comparable and Comparator interfaces are used for sorting objects. The main difference between Comparable and Comparator is: Comparable: It is used to define the natural ordering of the objects within the class.Comparator: It is used to define custom sorting logic externally.Difference
      5 min read

    • Java Comparator Interface
      The Comparator interface in Java is used to sort the objects of user-defined classes. The Comparator interface is present in java.util package. This interface allows us to define custom comparison logic outside of the class for which instances we want to sort. The comparator interface is useful when
      6 min read

    • Why to Use Comparator Interface Rather than Comparable Interface in Java?
      In Java, the Comparable and Comparator interfaces are used to sort collections of objects based on certain criteria. The Comparable interface is used to define the natural ordering of an object, whereas the Comparator interface is used to define custom ordering criteria for an object. Here are some
      8 min read

    • Sort an Array of Triplet using Java Comparable and Comparator
      Given an array of integer Triplet. you have to sort the array in ascending order with respect to the last element in the triplet. Examples: Input: { {1, 2, 3}, {2, 2, 4}, {5, 6, 1}, {10, 2, 10} } Output: { {5, 6, 1}, {1, 2, 3}, {2, 2, 4}, {10, 2, 10} } Input: { {10, 20, 30}, {40, -1, 2}, {30, 10, -1
      3 min read

    • Java Program to Sort LinkedList using Comparable
      In Java, LinkedList is a part of the collection framework provided in java.util package. LinkedList is a linear data structure where all the elements are unsorted in contiguous memory locations. The advantage of LinkedList is it is dynamic and easy to insert and delete any element. We can not access
      5 min read

    • How to Sort HashSet Elements using Comparable Interface in Java?
      The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means when we iterate the HashSet, there is no guarantee that we get elements in which order they were inserted. To sort HashSe
      3 min read

    • Sort LinkedHashMap by Values using Comparable Interface in Java
      The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. Assuming you have gone through LinkedHashMap in java and know about LinkedHashMap. Syntax: int compare(T obj) ; Illustration: Input : { GEEKS=1, geeks=3, for=2 } Output : { GEEKS=1
      2 min read

    • Sort LinkedHashMap by Keys using Comparable Interface in Java
      The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. To sort LinkedHashMap by key
      3 min read

    • How to Sort LinkedHashSet Elements using Comparable Interface in Java?
      The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
      3 min read

    Optional Class

    • Java 8 Optional Class
      Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very hard to avoid it without using too many null checks. So, to overcome this, Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many nu
      5 min read

    • Optional ofNullable() method in Java with examples
      The ofNullable() method of java.util.Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type. If the specified value is null, then this method returns an empty instance of the Optional class. Syntax: public static <T> Optional<
      2 min read

    • Optional orElse() method in Java with examples
      The orElse() method of java.util.Optional class in Java is used to get the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method returns the specified value. Syntax: public T orElse(T value) Parameters: This method accepts value as a pa
      2 min read

    • Optional ifPresentOrElse() method in Java with examples
      The ifPresentOrElse(Consumer, Runnable) method of java.util.Optional class helps us to perform the specified Consumer action the value of this Optional object. If a value is not present in this Optional, then this method performs the given empty-based Runnable emptyAction, passed as the second param
      2 min read

    • Optional orElseGet() Method in Java
      The orElseGet() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method returns the value generated from the specified supplier. Syntax of orElseGet() Methodpublic T orElseGet(S
      2 min read

    • Optional filter() method in Java with examples
      The filter() method of java.util.Optional class in Java is used to filter the value of this Optional instance by matching it with the given Predicate, and then return the filtered Optional instance. If there is no value present in this Optional instance, then this method returns an empty Optional in
      2 min read

    • Optional empty() method in Java with examples
      The empty() method of java.util.Optional class in Java is used to get an empty instance of this Optional class. This instance do not contain any value. Syntax: public static <T> Optional<T> empty() Parameters: This method accepts nothing. Return value: This method returns an empty instan
      1 min read

    • Optional hashCode() method in Java with examples
      The hashCode() method of java.util.Optional class in Java is used to get the hashCode value of this Optional instance. If there is no value present in this Optional instance, then this method returns 0. Syntax: public int hashCode() Parameter: This method do not accepts any parameter. Return Value:
      1 min read

    • Optional toString() method in Java with examples
      The toString() method of java.util.Optional class in Java is used to get the string representation of this Optional instance. Syntax: public String toString() Parameters: This method accepts nothing. Return value: This method returns the string representation of this Optional instance. Below program
      1 min read

    • Optional equals() method in Java with Examples
      The equals() method of java.util.Optional class in Java is used to check for equality of this Optional with the specified Optional. This method takes an Optional instance and compares it with this Optional and returns a boolean value representing the same. Syntax: public boolean equals(Object obj) P
      2 min read

    Date/Time API

    • New Date-Time API in Java 8
      New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API : Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and doesn't have setter methods.Less operations : In old API there are only few date operations
      6 min read

    • java.time.LocalDate Class in Java
      Java is the most popular programming language and widely used programming language. Java is used in all kind of application like as mobile application, desktop application, web application. In this Java java.time.LocalDate class is imported which represents to display the current date. java.time: It
      4 min read

    • java.time.LocalTime Class in Java
      Java is the most popular programming language and widely used programming language. Java is used in all kinds of applications like mobile applications, desktop applications, web applications. As in Java, java.time.LocalTime class represents time, which is viewed as hour-minute-second. This class is
      5 min read

    • java.time.LocalDateTime Class in Java
      java.time.LocalDateTime class, introduced in Java 8, represents a local date-time object without timezone information. The LocalDateTime class in Java is an immutable date-time object that represents a date in the yyyy-MM-dd-HH-mm-ss.zzz format. It implements the ChronoLocalDateTime interface and in
      4 min read

    • java.time.MonthDay Class in Java
      Java is the most popular programming language and widely used programming language. Java is used in all kinds of applications like mobile applications, desktop applications, web applications. The java.time.MonthDay class represents a combination of month and day of the month, and it is immutable. ja
      3 min read

    • java.time.OffsetTime Class in Java
      Java OffsetTime class is an immutable date-time object that represents a time, often viewed as hour-minute-second offset. OffsetTime class represents a time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 18:30:45+08:00, often viewed as an hour-minute-second-offset. This c
      7 min read

    • java.time.OffsetDateTime Class in Java
      Java is the most popular programming language and widely used programming language. Java is used in all kind of application like mobile application, desktop application, web application. In this Java java.time.OffsetDate, Time class is imported which is an immutable representation of a date-time wit
      4 min read

    • java.time.Clock Class in Java
      Java Clock class is present in java.time package. It was introduced in Java 8 and provides access to current instant, date, and time using a time zone. The use of the Clock class is not mandatory because all date-time classes also have a now() method that uses the system clock in the default time zo
      3 min read

    • java.time.ZonedDateTime Class in Java
      ZonedDateTime is an immutable object representing a date-time along with the time zone. This class stores all date and time fields.This class stores time to a precision of nanoseconds and a time-zone, with a zone Offset used to handle local date-times. For example, the value “2nd October 2011 at 14:
      8 min read

    • java.time.ZoneId Class in Java
      A ZoneId is used to identify the rules that used to convert between a LocalDateTime and an Instant of time. The actual rules, describing when and the way the offset changes, are defined by ZoneRules. This class is just an ID wont to obtain the underlying rules. The given approach has opted because t
      3 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences