Find Minimum Maximum Values in Java HashSet Example

This example shows how to find the minimum and maximum values from HashSet in Java. The example also shows how to get min or max element from HashSet using the Collections class.

How to find the minimum or maximum value from HashSet in Java?

There are a couple of ways using which we can find the minimum or maximum element from the HashSet in Java.

How to find the maximum value (biggest or highest value)?

1. Using the Collections class

The max method of the Collections class returns the maximum element of the HashSet object according to the natural ordering.

Example

Output

2. By iterating the HashSet

We can also iterate the HashSet object to find the maximum element as given below.

Output

How to find a minimum value (smallest or lowest value)?

1. Using the Collections class

The min method of the Collections class returns the minimum element of the HashSet object according to the natural ordering.

Example

Output

2. By iterating

We can also iterate through the HashSet to find the min element as given below.

Output

Collections class vs Iteration Performance

The min method and max method of the Collections class iterates the specified collection in order to find min and max elements respectively. So, there should not be any substantial difference between using these methods and iterating the HashSet to find the min or max values as far as performance is concerned.

How to find the min or max element from the HashSet of custom class objects?

If the HashSet elements are objects of a custom class, then the custom class must implement the Comparable interface or a custom Comparator object must be specified for the min or max methods to work.

If the custom class has implemented the Comparable interface, you can use the same min or max methods. If you want to provide a custom comparator object. the overloaded min or max methods should be used.

I am going to show how to find min or max custom class objects using the comparator.

Output

This example is a part of the HashSet in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 HashSet

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping