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:
Stream peek() Method in Java with Examples
Next article icon

Stream min() method in Java with Examples

Last Updated : 25 Jul, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional instance.

Syntax :

  Optional<T> min(Comparator<? super T> comparator)    Where, Optional is a container object which  may or may not contain a non-null value   and T is the type of objects  that may be compared by this comparator  

Exception : This method throws NullPointerException if the minimum element is null.

Example 1 : Minimum from list of Integers.




// Java code for Stream.min() method to get
// the minimum element of the Stream
// according to the provided Comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of integers
        List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
  
        // Using stream.min() to get minimum
        // element according to provided Integer Comparator
        Integer var = list.stream().min(Integer::compare).get();
  
        System.out.print(var);
    }
}
 
 

Output :

  -18  

Example 2 : Reverse comparator to get maximum value using min() function.




// Java code for Stream.min() method
// to get the minimum element of the 
// Stream according to provided comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of integers
        List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
  
        // Using Stream.min() with reverse
        // comparator to get maximum element.
        Optional<Integer> var = list.stream()
                    .min(Comparator.reverseOrder());
  
        // IF var is empty, then output will be Optional.empty
        // else value in var is printed.
        if(var.isPresent()){
        System.out.println(var.get());
        }
        else{
            System.out.println("NULL");
        }
          
    }
}
 
 

Output :

  25  

Example 3 : Comparing strings based on last characters.




// Java code for Stream.min() method
// to get the minimum element of the 
// Stream according to provided comparator.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // creating an array of strings
        String[] array = { "Geeks", "for", "GeeksforGeeks",
                           "GeeksQuiz" };
  
        // The Comparator compares the strings
        // based on their last characters and returns
        // the minimum value accordingly.
        Optional<String> MIN = Arrays.stream(array).min((str1, str2) -> 
                    Character.compare(str1.charAt(str1.length() - 1), 
                                      str2.charAt(str2.length() - 1)));
  
        // If a value is present,
        // isPresent() will return true
        if (MIN.isPresent()) 
            System.out.println(MIN.get()); 
        else
            System.out.println("-1"); 
    }
}
 
 

Output :

  for  


Next Article
Stream peek() Method in Java with Examples

S

Sahil_Bansall
Improve
Article Tags :
  • Java
  • Misc
  • Java - util package
  • Java-Functions
  • java-stream
  • Java-Stream interface
Practice Tags :
  • Java
  • Misc

Similar Reads

  • Stream skip() method in Java with examples
    Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N)
    3 min read
  • Optional stream() method in Java with examples
    The stream() method of java.util.Optional class in Java is used to get the sequential stream of the only value present in this Optional instance. If there is no value present in this Optional instance, then this method returns returns an empty Stream. Syntax: public Stream<T> stream() Paramete
    2 min read
  • Stream peek() Method in Java with Examples
    In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on ea
    2 min read
  • Stream.max() method in Java with Examples
    Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a spec
    3 min read
  • Stream mapToInt() in Java with examples
    Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream. Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream in
    2 min read
  • Stream count() method in Java with examples
    long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may travers
    2 min read
  • OptionalInt stream() method in Java with examples
    The stream() method help us to get value contain by OptionalInt as IntStream. If a value is present, method returns a sequential IntStream containing only that value, otherwise returns an empty IntStream. Syntax: public IntStream stream() Parameters: This method accepts nothing. Return value: This m
    1 min read
  • Stream noneMatch() Method in Java with Examples
    A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. noneMatch() of Stream class returns whether no elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determinin
    3 min read
  • OptionalLong stream() method in Java with examples
    The stream() method help us to get Long value contain by OptionalLong as LongStream.If a value is present, method returns a sequential LongStream containing only that value, otherwise returns an empty LongStream. Syntax: public LongStream stream() Parameters: This method accepts nothing. Return valu
    1 min read
  • PrintStream println() method in Java with Examples
    The println() method of PrintStream Class in Java is used to break the line in the stream. This method do not accepts any parameter or return any value. Syntax: public void println() Parameters: This method do not accepts any parameter. Return : This method do not returns any value. Below methods il
    2 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