Java Functional Interfaces
Last Updated : 15 Apr, 2025
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, lambda expressions and method references can be used to represent the instance of a functional interface.
Example: Using a Functional Interface with Lambda Expression
Java public class Geeks { public static void main(String[] args) { // Using lambda expression // to implement Runnable new Thread(() -> System.out.println("New thread created")).start(); } }
Explanation: In the above example, we can see the use of a lambda expression to implement the Runnable functional interface and create a new thread.
Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM interfaces. Functional interfaces in Java are a new feature that provides users with the approach of fundamental programming.
Note: A functional interface can also extend another functional interface.
The @FunctionalInterface annotation can be used to indicate that an interface is intended to be a functional interface. If an interface has more than one abstract method, it cannot be a functional interface.
@FunctionalInterface Annotation
@FunctionalInterface annotation is used to ensure that the functional interface cannot have more than one abstract method. In case more than one abstract methods are present, the compiler flags an "Unexpected @FunctionalInterface annotation" message. However, it is not mandatory to use this annotation.
Note: @FunctionalInterface annotation is optional but it is a good practice to use. It helps catching the error in early stage by making sure that the interface has only one abstract method.
Example: Defining a Functional Interface with @FunctionalInterface Annotation
Java // Define a functional interface @FunctionalInterface interface Square { int calculate(int x); } class Geeks { public static void main(String args[]) { int a = 5; // lambda expression to // define the calculate method Square s = (int x) -> x * x; // parameter passed and return type must be // same as defined in the prototype int ans = s.calculate(a); System.out.println(ans); } }
Explanation: In the above example, the Square interface is annotated as a functional interface. Then the lambda expression defines the calculate method to compute the square of the number.
Java Functional Interfaces Before Java 8
Before Java 8, we had to create anonymous inner class objects or implement these interfaces. Below is an example of how the Runnable interface was implemented prior to the introduction of lambda expressions.
Example:
Java // Java program to demonstrate functional interface // before Java 8 class Geeks { public static void main(String args[]) { // create anonymous inner class object new Thread(new Runnable() { @Override public void run() { System.out.println("New thread created"); } }).start(); } }
Built-In Java Functional Interfaces
Since Java SE 1.8 onwards, there are many interfaces that are converted into functional interfaces. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows:
- Runnable: This interface only contains the run() method.
- Comparable: This interface only contains the compareTo() method.
- ActionListener: This interface only contains the actionPerformed() method.
- Callable: This interface only contains the call() method.
Types of Functional Interfaces in Java
Java SE 8 included four main kinds of functional interfaces which can be applied in multiple situations as mentioned below:
- Consumer
- Predicate
- Function
- Supplier
1. Consumer
The consumer interface of the functional interface is the one that accepts only one argument or a gentrified argument. The consumer interface has no return value. It returns nothing. There are also functional variants of the Consumer — DoubleConsumer, IntConsumer, and LongConsumer. These variants accept primitive values as arguments.
Other than these variants, there is also one more variant of the Consumer interface known as Bi-Consumer.
Syntax / Prototype of Consumer Functional Interface:
Consumer<Integer> consumer = (value) -> System.out.println(value);
This implementation of the Java Consumer functional interface prints the value passed as a parameter to the print statement. This implementation uses the Lambda function of Java.
2. Predicate
The Predicate interface represents a boolean-valued function of one argument. It is commonly used for filtering operations in streams.
Just like the Consumer functional interface, Predicate functional interface also has some extensions. These are IntPredicate, DoublePredicate, and LongPredicate. These types of predicate functional interfaces accept only primitive data types or values as arguments.
Syntax:
public interface Predicate<T> {
boolean test(T t);
}
The Java predicate functional interface can also be implemented using Lambda expressions.
Predicate predicate = (value) -> value != null;
3. Function
A function is a type of functional interface in Java that receives only a single argument and returns a value after the required processing. Many different versions of the function interfaces are instrumental and are commonly used in primitive types like double, int, long.
Syntax:
Function<Integer, Integer> function = (value) -> value * value;
- Bi-Function: The Bi-Function is substantially related to a Function. Besides, it takes two arguments, whereas Function accepts one argument.
- Unary Operator and Binary Operator: There are also two other functional interfaces which are named as Unary Operator and Binary Operator. They both extend the Function and Bi-Function respectively, where both the input type and the output type are same.
4. Supplier
The Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output.
The different extensions of the Supplier functional interface hold many other suppliers functions like BooleanSupplier, DoubleSupplier, LongSupplier, and IntSupplier. The return type of all these further specializations is their corresponding primitives only.
Syntax:
Supplier<String> supplier = () -> "Hello, World!";
Functional Interfaces Table
Functional Interfaces | Description | Method |
---|
Runnable | It represents a task that can be executed by a thread. | void run() |
---|
Comparable | It compares two objects for ordering. | int compareTo(T o) |
---|
ActionListener | It handles an action event in event-driven programming. | void actionPerformed(ActionEvent e) |
---|
Callable | It represents a task that can return a result or throw an exception. | V call() throws Exception |
---|
Consumer | It accepts a single input argument and returns no result. | void accept(T t) |
---|
Predicate | It accepts a single argument and returns a boolean result. | boolean test(T t) |
---|
Function | It accepts a single argument and returns a result. | R apply(T t) |
---|
Supplier | It does not take any arguments but provides a result. | T get() |
---|
BiConsumer | It accepts two arguments and returns no result. | void accept(T t, U u) |
---|
BiPredicate | It accepts two arguments and returns a boolean result. | boolean test(T t, U u) |
---|
BiFunction | It accepts two arguments and returns a result. | R apply(T t, U u) |
---|
UnaryOperator | This is a special case of Function, where input and output types are the same. | T apply(T t) |
---|
BinaryOperator | This is a special case of BiFunction, where input and output types are the same. | T apply(T t1, T t2) |
---|
Example: Using Predicate Interface to Filter Strings
Java // Demonstrate Predicate Interface import java.util.*; import java.util.function.Predicate; class Geeks { public static void main(String args[]) { // create a list of strings List<String> n = Arrays.asList( "Geek", "GeeksQuiz", "g1", "QA", "Geek2"); // declare the predicate type as string and use // lambda expression to create object Predicate<String> p = (s) -> s.startsWith("G"); // Iterate through the list for (String st : n) { // call the test method if (p.test(st)) System.out.println(st); } } }
OutputGeek GeeksQuiz Geek2
Important Points:
- In functional interfaces, there is only one abstract method supported. If the annotation of a functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functions, that interface will not be called a functional interface. It is called a non-functional interface.
- There is no such need for the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking the compiler level. Besides this, it is optional.
- An infinite number of methods (whether static or default) can be added to the functional interface. In simple words, there is no limit to a functional interface containing static and default methods.
- Overriding methods from the parent class do not violate the rules of a functional interface in Java. In functional interface overriding methods from the parent class does not count as abstract method.
- The java.util.function package contains many built-in functional interfaces in Java 8.
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 ExpressionsLambda 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 Expre
5 min read
Java - Lambda Expressions ParametersLambda 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 CollectionsIn 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 ExamplesVariable 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 JavaHere 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 JavaLambda 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 JavaOne 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 ExpressionA 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 ExpressionLambda 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 JavaBelow 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 InterfacesA 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 ExamplesThe 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 ExamplesThe 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 ExamplesA 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 JavaThe 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:
6 min read
Supplier Interface in Java with ExamplesThe 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
Streams
Java 8 Stream TutorialJava 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 JavaCollection 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 StreamsMany 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 â FiltersIn 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 JavaPrerequisite: 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, f
5 min read
Functional Programming in Java 8+ using the Stream API with ExampleAPI 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 JavaThe 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 StreamIn 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 JavaPrerequisite : 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 // Java code for converting string array // t
3 min read
10 Ways to Create a Stream in JavaThe 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 JavaA 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 JavaAn 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 JavaAn 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 GenericsJava 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 JavaThe 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 JavaA 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 JavaA 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 JavaA 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 JavaIntroduced 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 JavaGiven 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 examplesStream 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 examplesStream 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 JavaStream 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 examplesStream 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 examplesStream 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 examplesStream 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 examplesStream 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 JavaStream 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 JavaStream 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 ComparatorIn 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 InterfaceThe 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
7 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 r
8 min read
Sort an Array of Triplet using Java Comparable and ComparatorGiven 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 ComparableIn 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 JavaThe 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 JavaThe 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 ClassEvery 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 examplesThe 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 examplesThe 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 examplesThe 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 JavaThe 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(Su
2 min read
Optional filter() method in Java with examplesThe 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 examplesThe 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 examplesThe 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 examplesThe 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 ExamplesThe 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 8New 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 JavaJava 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 JavaJava 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 Javajava.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 JavaJava 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 JavaJava 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 JavaJava 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 JavaJava 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 JavaZonedDateTime 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 JavaA 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