How do you find the maximum element in an ArrayList?

Find maximum element of ArrayList with Java Collections

Java 8Object Oriented ProgrammingProgramming



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 −

Finding the Minimum or Maximum Value in Java ArrayList

The minimum value is the one with the smallest value and the maximum value is the one with the largest value. The main task here is to find the minimum and maximum value from the ArrayList. Consider an example of an ArrayList, and we need to find the largest and the smallest element.

Example:

Input List: {10, 20, 8, 32, 21, 31}; Output: Maximum is: 32 Minimum is: 8

Method 1: By iterating over ArrayList values

  1. First, we need to initialize the ArrayList values.
  2. Then the length of the ArrayList can be found by using the size() function.
  3. After that, the first element of the ArrayList will be store in the variable min and max.
  4. Then the for loop is used to iterate through the ArrayList elements one by one in order to find the minimum and maximum from the array list.




// Java program to find the minimum and

// maximum value of the ArrayList

import java.util.*;

public class Max {

public static void main(String args[])

{

// initializing the ArrayList elements

ArrayList<Integer> arr = new ArrayList<>();

arr.add(10);

arr.add(20);

arr.add(8);

arr.add(32);

arr.add(21);

arr.add(31);

int min = arr.get(0);

int max = arr.get(0);

// store the length of the ArrayList in variable n

int n = arr.size();

// loop to find minimum from ArrayList

for (int i = 1; i < n; i++) {

if (arr.get(i) < min) {

min = arr.get(i);

}

}

// loop to find maximum from ArrayList

for (int i = 1; i < n; i++) {

if (arr.get(i) > max) {

max = arr.get(i);

}

}

// The result will be printed

System.out.println("Maximum is : " + max);

System.out.println("Minimum is : " + min);

}

}

Output Maximum is : 32 Minimum is : 8

Method 2: Using Collection class Methods



We can use the min() and max() method of the collection class of Java. Collections in java is basically a framework that provides an architecture to accumulate and handle the group of objects. Java Collection framework provides many classes such as ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet.

Approach:

  1. First, we need to create a class.
  2. Then an integer ArrayList needs to be created to store the elements. After that, the length of the ArrayList should be calculated with the help of the size() method.
  3. The length of the ArrayList will be used to iterate through the loop and print the elements of the ArrayList.
  4. Then, the min and max method of collection class will be used to find the minimum and maximum from the ArrayList and will store in the min and max variable and then the result will be printed on the screen.




// Java program to find the minimum and

// maximum element of the list using

// Collection class's method

import java.util.ArrayList;

import java.util.Collections;

public class MinMax {

public static void main(String args[])

{

// Creating arraylist

ArrayList<Integer> arr = new ArrayList<Integer>();

// Adding object in arraylist

arr.add(10);

arr.add(20);

arr.add(5);

arr.add(8);

// Finding the size of ArrayList

int n = arr.size();

// printing the ArrayList elements

System.out.println("ArrayList elements are :");

for (int i = 0; i < n; i++) {

System.out.print(arr.get(i) + " ");

}

System.out.println();

// Finding the minimum and maximum from the

// arraylist using min and max method of collection

// class

int max = Collections.max(arr);

System.out.println("Maximum is : " + max);

int min = Collections.min(arr);

System.out.println("Minimum is : " + min);

}

}

Output Array elements are : 10 20 5 8 Maximum is : 20 Minimum is : 5

Method 3: By sorting the ArrayList

  1. First, we need to import the Collections class, because in the Collections class there is a method called Collections.sort() which we need to sort the unsorted array.
  2. After that, the ArrayList of integers will be created and then we will calculate the length using size() function.
  3. Then, the ArrayList will be sorted using the predefined function, and by default, it will be sorted in increasing order only.
  4. For finding minimum and maximum values from the ArrayList, we simply need to find the first and last element of the ArrayList, because the ArrayList is sorted in ascending order then the first element will be the smallest and the last element will be largest among all of the elements.
  5. The first element can be found by using arr.get(0), because it is present in the first position and the index of the array is started from 0.
  6. The last element can be found by using arr.get(n-1), since n is the size of the array and array index is started from 0, that’s why we need to find the element that is in index n-1. Also, this is a sorted ArrayList then the largest element is present at the end.




// Java program to get the minimum and

// maximum value after the sorting the ArrayList

// using Collection class function

import java.util.*;

import java.util.Collections;

public class MaxMinSort {

public static void main(String args[])

{

// Creating arraylist

ArrayList<Integer> arr = new ArrayList<Integer>();

// Adding object in arraylist

arr.add(10);

arr.add(12);

arr.add(5);

arr.add(8);

arr.add(21);

arr.add(16);

arr.add(15);

// Storing the size of the ArrayList in variable n

int n = arr.size();

int i;

System.out.println("Elements of the ArrayList : ");

for (i = 0; i < n; i++) {

System.out.print(arr.get(i) + " ");

}

System.out.println();

// The ArrayList will be sorted using predefined

// function

Collections.sort(arr);

System.out.println("ArrayList after sorting : ");

for (i = 0; i < n; i++) {

System.out.print(arr.get(i) + " ");

}

System.out.println();

// First and last element of the ArrayList gets stored

// into min and max variable

int min = arr.get(0);

int max = arr.get(n - 1);

System.out.println("Maximum is : " + max);

System.out.println("Minimum is : " + min);

}

}

Output Elements of the array : 10 12 5 8 21 16 15 Arrays after sorting : 5 8 10 12 15 16 21 Maximum is : 21 Minimum is : 5

How do you find the maximum element in an ArrayList?




Article Tags :

Java

Java Programs

Java-ArrayList

Practice Tags :

Java

1. Introduction


In this article, We'll learn how to find the maximum (max) value from ArrayList. Finding the max value from ArrayList from Collection API is done by running a loop over all the elements or can be found max value with the Collections.max() method.

Collections.max(): Returns the maximum element of the given collection, according to the natural ordering of its elements.

Example programs to find the max value from a list of wrapper objects and a list of custom or user-defined objects.


How to find the Minimum Maximum value in ArrayList?

There are a couple of ways to find minimum and maximum value in Java ArrayList.

1) Find Min Max value in ArrayList using Collections class

You can use min and max methods of Collections class.

1

static <T extends Object & Comparable<? super T>min(Collection<? extends T> c)

This method returns the minimum element/value of the specified collection according to the natural ordering of the elements.

1

static <T extends Object & Comparable<? super T>max(Collection<? extends T> c)

This method returns the maximum element/value of the specified collection according to the natural ordering of the elements.

Example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

package com.javacodeexamples.collections.arraylist;

import java.util.ArrayList;

import java.util.Collections;

public class FindMinMaxValueArrayListExample {

public static void main(String[] args) {

/*

* ArrayList containing student marks

*/

ArrayList<Integer> aListMarks = new ArrayList<Integer>();

//add elements to ArrayList

aListMarks.add(53);

aListMarks.add(67);

aListMarks.add(89);

aListMarks.add(43);

aListMarks.add(87);

aListMarks.add(71);

aListMarks.add(63);

aListMarks.add(45);

aListMarks.add(69);

aListMarks.add(53);

/*

* To find minimum value in ArrayList, use

* min method of Collections class.

*/

System.out.println( "ArrayList Min Value: " + Collections.min(aListMarks) );

/*

* To find maximum value in ArrayList, use

* max method of Collections class.

*/

System.out.println( "ArrayList Max Value: " + Collections.max(aListMarks) );

}

}

Output

1

2

ArrayList Min Value: 43

ArrayList Max Value: 89

How to find an index of minimum maximum elements in Java ArrayList?

If you want to find index of minimum or maximum element instead of value, you can use indexOf method of the ArrayList class.

1

int indexOf(Object o)

This method returns the index of the specified element. If the element is not found in the ArrayList, it returns -1.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

ArrayList<Integer> aListMarks = new ArrayList<Integer>();

//add elements to ArrayList

aListMarks.add(53);

aListMarks.add(67);

aListMarks.add(89);

aListMarks.add(43);

aListMarks.add(87);

aListMarks.add(71);

aListMarks.add(63);

aListMarks.add(45);

aListMarks.add(69);

aListMarks.add(53);

/*

* To find minimum value in ArrayList, use

* min method of Collections class.

*

* To get the index of an element, use indexOf method.

*/

System.out.println( "ArrayList Min Value is at index: "

+ aListMarks.indexOf(Collections.min(aListMarks)) );

/*

* To find maximum value in ArrayList, use

* max method of Collections class.

* To get the index of an element, use indexOf method.

*/

System.out.println( "ArrayList Max Value is at index: "

+ aListMarks.indexOf(Collections.max(aListMarks)) );

Output

1

2

ArrayList Min Value is at index: 3

ArrayList Max Value is at index: 2

2) Find Min Max value in ArrayList using for loop

If you want to find min max values without using the Collections class, you can use for loop to find the same as given below.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

package com.javacodeexamples.collections.arraylist;

import java.util.ArrayList;

public class FindMinMaxValueArrayListExample {

public static void main(String[] args) {

/*

* ArrayList containing student marks

*/

ArrayList<Integer> aListMarks = new ArrayList<Integer>();

//add elements to ArrayList

aListMarks.add(53);

aListMarks.add(67);

aListMarks.add(89);

aListMarks.add(43);

aListMarks.add(87);

aListMarks.add(71);

aListMarks.add(63);

aListMarks.add(45);

aListMarks.add(69);

aListMarks.add(53);

//declare min and max value as the first element of the list

int min = aListMarks.get(0);

int max = aListMarks.get(0);

//declare min and max elements index as 0 (i.e. first element)

int minIndex = 0, maxIndex = 0;

//Iterate through ArrayList

for(int i = 1; i < aListMarks.size(); i++ ){

/*

* If current value is less than min value, it

* is new minimum value

*/

if( aListMarks.get(i) < min ){

min = aListMarks.get(i);

minIndex = i;

}

/*

* If current value is greater than max value, it

* is new maximum value.

*/

if( aListMarks.get(i) > max ){

max = aListMarks.get(i);

maxIndex = i;

}

}

System.out.println("ArrayList Min Value is: "

+ min

+ ", Found at index: "

+ minIndex

);

System.out.println("ArrayList Max Value is: "

+ max

+ ", Found at index: "

+ maxIndex

);

}

}

Output

1

2

ArrayList Min Value is: 43, Found at index: 3

ArrayList Max Value is: 89, Found at index: 2

This example is a part of theJava ArrayList tutorial with examples.

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

Find maximum element of Java ArrayList : ArrayList«Collections Data Structure«Java






  1. Java
  2. Collections Data Structure
  3. ArrayList

Find maximum element of Java ArrayList

import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(new Integer("3")); arrayList.add(new Integer("1")); arrayList.add(new Integer("8")); arrayList.add(new Integer("3")); arrayList.add(new Integer("5")); Object obj = Collections.max(arrayList); System.out.println(obj); } } //8








1.Get the size of an arraylist after and before add and remove methods
2.Use the Iterator returned from ArrayList to loop through an array list
3.Get generic Iterator from generic ArrayList
4.Convert an ArrayList into an array.
5.Pre-generics example that uses a collection.
6.shows the modern, generic form of collection classes
7.Use set method to change the value in an array list
8.Store user-defined objects in arraylist
9.pass the actual object you want removed.
10.Convert a List (ArrayList) to an Array with zero length array
11.Convert a List (ArrayList) to an Array with full length array
12.Remove duplicate items from an ArrayList
13.Looping through a Collection object: while loop, iterator, and for each
14.Append all elements of other Collection to Java ArrayList
15.Copy all elements of Java ArrayList to an Object Array
16.Get Size of Java ArrayList and loop through elements
17.Add an element to specified index of Java ArrayList
18.Get Sub List of Java ArrayList
19.Insert all elements of other Collection to Specified Index of Java ArrayList
20.Iterate through elements Java ArrayList using Iterator
21.Iterate through elements Java ArrayList using ListIterator
22.Remove all elements from Java ArrayList
23.Remove an element from specified index of Java ArrayList
24.Search an element of Java ArrayList
25.Get element in an ArrayList by index
26.Replace an element at specified index of Java ArrayList
27.Sort elements of Java ArrayList
28.Copy Elements of ArrayList to Java Vector
29.Copy Elements of One Java ArrayList to Another Java ArrayList
30.Find Minimum element of Java ArrayList
31.Get Enumeration over Java ArrayList
32.Get Synchronized List from Java ArrayList
33.Perform Binary Search on Java ArrayList
34.Replace All Elements Of Java ArrayList
35.Replace all occurrences of specified element of Java ArrayList
36.Reverse order of all elements of Java ArrayList
37.Shuffle elements of Java ArrayList
38.Swap elements of Java ArrayList
39.Iterate through a Collection using Java Iterator
40.Sort Java ArrayList in descending order using comparator
41.Remove an element from Collection using Java Iterator
42.Replace an element from ArrayList using Java ListIterator
43.How to Convert an ArrayList into an array
44.Sort items of an ArrayList
45.Rotate elements of a collection
46.Search collection element
47.If an ArrayList contains a given item
48.Convert Collection to ArrayList?
49.A boolean is being stored and then retrieved from an ArrayList
50.Traverse through ArrayList in reverse direction using Java ListIterator
51.Traverse through ArrayList in forward direction using Java ListIterator
52.Remove an element from ArrayList using Java ListIterator
53.Get Previous and next index using Java ListIterator
54.A Map implemented with ArrayLists
55.A variant of java.util.ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array
56.Copy On Write ArrayList
57.This program demonstrates the ArrayList class
58.ArrayList with sorted contents.

Example

package com.w3spoint; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test { public static void main(String a[]){ List<Integer> list = new ArrayList<Integer>(); list.add(32); list.add(61); list.add(73); list.add(10); list.add(9); list.add(86); System.out.println("Maximum element from the list: "+Collections.max(list)); } }

package com.w3spoint; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test { public static void main(String a[]){ List<Integer> list = new ArrayList<Integer>(); list.add(32); list.add(61); list.add(73); list.add(10); list.add(9); list.add(86); System.out.println("Maximum element from the list: "+Collections.max(list)); } }