Javatpoint Logo
Javatpoint Logo

Java Collections max() Method

The max() is a Java Collections class method which returns the maximum value for the given inputs. All elements in the collection must implement the Comparable interface. There is two different types of Java max() method which can be differentiated depending on its parameter. These are:

  1. Java Collections max(coll) Method
  2. Java Collections min(coll, comp) Method

Java Collections max(coll) Method

The max() method of Java Collections class is used to get the maximum element of the given collection, according to the natural ordering of its elements.

Java Collections max(coll, comp) Method

The max() method of Java Collections class is used to get the maximum element of the given collection, according to the order induced by the specified comparator.

Syntax

Following is the declaration of max() method:

Parameter

Parameter Description Required/Optional
coll It is the collection whose maximum element is to be determined. Required
comp It is the comparator with which we determine the maximum element. Required

Returns

Method Returns
max(Collection<? extends T> coll) It returns the maximum element of the given collection, according to the natural ordering of its elements.
max(Collection<? extends T> coll, Comparator<? super T> comp) It returns the maximum element of the given collection, according to the order of the specified comparable.

Exceptions

The max() method throws the following exceptions-

ClassCastException- It throws this exception if the collection contains elements that are not mutually comparable (for example, strings and integers).

NoSuchElementException- It throws this exception if the collection is empty.

Compatibility Version

Java 1.4 and above

Example 1

Test it Now

Output:

Max val: S

Example 2

Test it Now

Output:

Maximum element is: 250

Example 3

Test it Now

Output:

Output: 101

Example 4

Test it Now

Output:

Maximum Element is: XML
Maximum Value is: -10






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA