How to Find the Minimum or Maximum Element from LinkedHashSet in Java?

Given a LinkedHashSet the task is to find the minimum and maximum element from this LinkedHashSet in Java. There are two ways to find the minimum or maximum element from LinkedHashSet in Java as follows
- Using the min and max method of the Collections class
- By Iterating the LinkedHashSet
Examples:
Input : LinkedHashset : {1, 56, 8, 24, 50}
Output: Maximum Element: 56
Minimum Element: 1
Input : LinkedHashset : {2, 34, 100, 29, 30}
Output: Maximum Element: 100
Minimum Element: 2
Approach 1:
The max and min method of the Collections class returns the maximum and minimum element of the specified collection object.
- Collections.max(Object obj): Accepts the collection object.
- Collections.min(Object obj): Accepts the collection object.
Following Java code finds the minimum and maximum element from LinkedHashSet using predefined min, max method of the Collections class.
Java
// Java Program to find the minimum or// maximum element from LinkedHashSeimport java.io.*;import java.util.*;Â
class Main {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // create a new LinkedHashSet        LinkedHashSet<Integer> lhs            = new LinkedHashSet<Integer>();Â
        // add elements to LinkedHashSet        lhs.add(1);        lhs.add(56);        lhs.add(8);        lhs.add(24);        lhs.add(50);Â
        // finding maximum and minimum using inbuilt        // functions        int maximum = Collections.max(lhs);        int minimum = Collections.min(lhs);Â
        System.out.println("Maximum element: " + maximum);        System.out.println("Minimum element: " + minimum);    }} |
Â
Â
Maximum element: 56 Minimum element: 1
Approach 2:
Â
Iterate over the LinkedHashSet using enhanced for loop or iterator and find the maximum and minimum element.
Â
Consider the following Java code which finds the maximum and minimum element by iterating over each element in the LinkedHashSet.
Â
Java
// Java Program to find the minimum or// maximum element from LinkedHashSetimport java.io.*;import java.util.*;Â
class Main {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // create a new LinkedHashSet        LinkedHashSet<Integer> lhs            = new LinkedHashSet<Integer>();Â
        // add elements to LinkedHashSet        lhs.add(1);        lhs.add(56);        lhs.add(8);        lhs.add(24);        lhs.add(50);Â
        // Iterate over the LinkedHashSet        int maximum = Integer.MIN_VALUE;        int minimum = Integer.MAX_VALUE;Â
        for (Integer num : lhs) {            if (maximum < num)                maximum = num;        }Â
        for (Integer num : lhs) {            if (minimum > num)                minimum = num;        }Â
        System.out.println("Maximum element: " + maximum);        System.out.println("Minimum element: " + minimum);    }} |
Â
Â
Maximum element: 56 Minimum element: 1
Â



