Find Minimum Maximum LinkedHashSet Element in Java Example

This example shows how to find the minimum or maximum element from LinkedHashSet in Java. This example also shows how to find min or max elements from LinkedHashSet using the Collections class.

How to find the minimum or maximum element from LinkedHashSet in Java?

There are a couple of ways using which we can find min or max values from the LinkedHashSet as given below.

How to find the Maximum element (max element, largest element, biggest element)?

1. Using the max method of the Collections class

The max method of the Collections class returns the maximum element of the specified collection object.

The maximum element is decided based on the element’s natural order.

Output

2. By iterating the LinkedHashSet

We can also iterate through elements of LinkedHashSet object using the enhanced for loop or an iterator and find the maximum element as given below.

Output

How to find the Minimum element (min element, lowest element, smallest element)?

1. Using the min method of the Collections class

The min method of the Collections class returns the minimum element of the specified collection object.

The minimum element is decided based on the element’s natural order.

Output

2. By iterating the LinkedHashSet

We can also iterate through elements of LinkedHashSet object using the enhanced for loop or an iterator and find the minimum element as given below.

Output

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

If the LinkedHashSet elements are objects of a custom class, then the custom class either must implement the Comparable interface for the min and max methods to work or a custom Comparator must be provided in the overloaded min or max method that also accepts a comparator object.

I will show you how to use the Comparable interface to find min or max element of the custom class.

Output

We can also provide a custom comparator object in the overloaded min and max methods instead of implementing the Comparable interface in our custom class.

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

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

References:
Java 8 LinkedHashSet

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