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:
Program to Convert List to Stream in Java
Next article icon

Program to convert a Set to Stream in Java using Generics

Last Updated : 11 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Below are the various methods to convert Set to Stream.

  1. Using Collection.stream(): This method involves directly converting the Set to Stream using Collection.stream() method.

    Algorithm:

    1. Get the Set to be converted.
    2. Convert Set to Stream. This is done using Set.stream().
    3. Return/Print the Stream.




    // Java Program to convert
    // Set to Stream in Java 8
      
    import java.util.*;
    import java.util.stream.*;
    import java.util.function.*;
      
    class GFG {
      
        // Generic function to convert a set to stream
        private static <T> Stream<T> convertSetToStream(Set<T> set)
        {
            return set.stream();
        }
      
        // Main method
        public static void main(String args[])
        {
            // Create a set of String
            Set<Integer> setOfInteger = new HashSet<>(
                Arrays.asList(2, 4, 6, 8, 10));
      
            // Print the set of Integer
            System.out.println("Set of Integer: " + setOfInteger);
      
            // Convert Set of Stream
            Stream<Integer>
                streamOfInteger = convertSetToStream(setOfInteger);
      
            // Print the Stream of Integer
            System.out.println("Stream of Integer: "
                               + Arrays.toString(
                                 streamOfInteger.toArray()));
        }
    }
     
     
    Output:
      Set of Integer: [2, 4, 6, 8, 10]  Stream of Integer: [2, 4, 6, 8, 10]  
  2. Using Predicate to filter the Stream: In this method filter(Predicate) method is used that returns a stream consisting of elements that match the given predicate condition. The Functional Interface Predicate is defined in the java.util.Function package and can therefore be used as the assignment target for a lambda expression or method reference. It improves manageability of code, helps in unit-testing them separately

    Algorithm:

    1. Get the Set to be converted.
    2. Define the Predicate condition by either using pre-defined static methods or by creating a new method by overriding the Predicate interface. In this program, the interface is overridden to match the strings that start with “G”.
    3. Convert Set to Stream. This is done using Set.stream().
    4. Filter the obtained stream using the defined predicate condition
    5. The required Stream has been obtained. Return/Print the Stream.




    // Java Program to convert
    // Set to Stream in Java 8
      
    import java.util.*;
    import java.util.stream.*;
    import java.util.function.*;
      
    class GFG {
      
        // Generic function to convert a set to stream
        private static <T> Stream<T>
        convertSetToStream(Set<T> set, Predicate<T> predicate)
        {
            return set.stream()
                .filter(predicate);
        }
      
        // Main method
        public static void main(String args[])
        {
            // Create a set of String
            Set<String>
                setOfString = new HashSet<>(
                    Arrays.asList("GeeksForGeeks",
                                  "A computer portal",
                                  "for",
                                  "Geeks"));
      
            // Print the set of String
            System.out.println("Set of String: " + setOfString);
      
            // Create the predicate for item starting with G
            Predicate<String> predicate = new Predicate<String>() {
                @Override
                public boolean test(String s)
                {
                    // filter items that start with "G"
                    return s.startsWith("G");
                }
            };
      
            // Convert Set of Stream
            Stream<String>
                streamOfString = convertSetToStream(setOfString, predicate);
      
            // Print the filter Stream of String
            System.out.println("Stream from List with items"
                               + " starting with G: ");
      
            System.out.println(Arrays.toString(
                streamOfString.toArray()));
        }
    }
     
     
    Output:
      Set of String: [for, Geeks, GeeksForGeeks, A computer portal]  Stream from List with items starting with G:   [Geeks, GeeksForGeeks]  


Next Article
Program to Convert List to Stream in Java

R

RishabhPrabhu
Improve
Article Tags :
  • Java
  • java-set
  • Java-Set-Programs
  • java-stream
  • Java-Stream-programs
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