How to Query Maximum Element of HashSet in Java


In this example we will show how to find a maximum element of Java HashSet with max method of Collections class.

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.HashSet;

public class FindMaxElementHashSet {

	public static void main(String[] args) {

		HashSet hs = new HashSet();
		// Add elements
		hs.add(20);
		hs.add(22);
		hs.add(30);
		hs.add(26);

		// Use the Max () method in the Collections utility class to find the
		// largest elements
		Integer max = Collections.max(hs);

		System.out.println("The largest element:" + max);

	}

}

Output:

The largest element:30

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments