
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Element of ArrayList with Java Collections
In order to compute maximum element of ArrayList with Java Collections, we use the Collections.max() method. The java.util.Collections.max() returns the maximum element of the given collection. All elements must be mutually comparable and implement the comparable interface. They shouldn’t throw a ClassCastException.
Declaration −The Collections.max() method is declared as follows −
public static <T extends Object & Comparable> T max(Collection c)
where c is the collection object whose maximum is to be found.
Let us see a program to find the maximum element of ArrayList with Java collections −
Example
import java.util.*; public class Example { public static void main (String[] args) { List<Integer> list = new ArrayList<Integer>(); try { list.add(14); list.add(2); list.add(73); System.out.println("Maximum element : " + Collections.max(list)); } catch (ClassCastException | NoSuchElementException e) { System.out.println("Exception caught : " + e); } } }
Output
Maximum element : 73
Advertisements