Как найти максимальный элемент списка java

There is an ArrayList which stores integer values. I need to find the maximum value in this list. E.g. suppose the arrayList stored values are : 10, 20, 30, 40, 50 and the max
value would be 50.

What is the efficient way to find the maximum value?

@Edit : I just found one solution for which I am not very sure

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(100); /* add(200), add(250) add(350) add(150) add(450)*/

Integer i = Collections.max(arrayList)

and this returns the highest value.

Another way to compare the each value e.g. selection sort or binary sort algorithm
 

Line's user avatar

Line

1,5193 gold badges18 silver badges41 bronze badges

asked Nov 29, 2011 at 1:35

user1010399's user avatar

5

You can use the Collections API to achieve what you want easily — read efficiently — enough
Javadoc for Collections.max

Collections.max(arrayList);

Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface.

nanosoft's user avatar

nanosoft

2,8244 gold badges38 silver badges58 bronze badges

answered Nov 29, 2011 at 1:38

gotomanners's user avatar

gotomannersgotomanners

7,7731 gold badge24 silver badges39 bronze badges

2

This question is almost a year old but I have found that if you make a custom comparator for objects you can use Collections.max for an array list of objects.

import java.util.Comparator;

public class compPopulation implements Comparator<Country> {
    public int compare(Country a, Country b) {
        if (a.getPopulation() > b.getPopulation())
            return -1; // highest value first
        if (a.getPopulation() == b.Population())
            return 0;
        return 1;
    }
}
ArrayList<Country> X = new ArrayList<Country>();
// create some country objects and put in the list
Country ZZ = Collections.max(X, new compPopulation());

Tom's user avatar

Tom

16.6k17 gold badges44 silver badges54 bronze badges

answered Aug 31, 2013 at 10:17

Robert Quinn's user avatar

3

public int getMax(ArrayList list){
    int max = Integer.MIN_VALUE;
    for(int i=0; i<list.size(); i++){
        if(list.get(i) > max){
            max = list.get(i);
        }
    }
    return max;
}

From my understanding, this is basically what Collections.max() does, though they use a comparator since lists are generic.

answered May 30, 2013 at 15:41

John's user avatar

JohnJohn

2893 silver badges2 bronze badges

2

We can simply use Collections.max() and Collections.min() method.

public class MaxList {
    public static void main(String[] args) {
        List l = new ArrayList();
        l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        l.add(5);
        System.out.println(Collections.max(l)); // 5
        System.out.println(Collections.min(l)); // 1
    }
}

answered Oct 23, 2013 at 16:02

Bhavin Shah's user avatar

Bhavin ShahBhavin Shah

1,28713 silver badges14 bronze badges

0

Comparator.comparing

In Java 8, Collections have been enhanced by using lambda. So finding max and min can be accomplished as follows, using Comparator.comparing:

Code:

List<Integer> ints = Stream.of(12, 72, 54, 83, 51).collect(Collectors.toList());
System.out.println("the list: ");
ints.forEach((i) -> {
    System.out.print(i + " ");
});
System.out.println("");
Integer minNumber = ints.stream()
        .min(Comparator.comparing(i -> i)).get();
Integer maxNumber = ints.stream()
        .max(Comparator.comparing(i -> i)).get();

System.out.println("Min number is " + minNumber);
System.out.println("Max number is " + maxNumber);

Output:

 the list: 12 72 54 83 51  
 Min number is 12 
 Max number is 83

Basil Bourque's user avatar

Basil Bourque

297k100 gold badges831 silver badges1141 bronze badges

answered Jun 26, 2014 at 18:39

Kick Buttowski's user avatar

Kick ButtowskiKick Buttowski

6,69913 gold badges37 silver badges58 bronze badges

Integer class implements Comparable.So we can easily get the max or min value of the Integer list.

public int maxOfNumList() {
    List<Integer> numList = new ArrayList<>();
    numList.add(1);
    numList.add(10);
    return Collections.max(numList);
}

If a class does not implements Comparable and we have to find max and min value then we have to write our own Comparator.

List<MyObject> objList = new ArrayList<MyObject>();
objList.add(object1);
objList.add(object2);
objList.add(object3);
MyObject maxObject = Collections.max(objList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        if (o1.getValue() == o2.getValue()) {
            return 0;
        } else if (o1.getValue() > o2.getValue()) {
            return -1;
        } else if (o1.getValue() < o2.getValue()) {
            return 1;
        }
        return 0;
    }
});

bluish's user avatar

bluish

26k27 gold badges120 silver badges179 bronze badges

answered Feb 26, 2017 at 8:39

Avijit Karmakar's user avatar

Avijit KarmakarAvijit Karmakar

8,6846 gold badges42 silver badges59 bronze badges

There is no particularly efficient way to find the maximum value in an unsorted list — you just need to check them all and return the highest value.

answered Nov 29, 2011 at 1:38

Brendan Long's user avatar

Brendan LongBrendan Long

52.9k21 gold badges144 silver badges186 bronze badges

3

Here are three more ways to find the maximum value in a list, using streams:

List<Integer> nums = Arrays.asList(-1, 2, 1, 7, 3);
Optional<Integer> max1 = nums.stream().reduce(Integer::max);
Optional<Integer> max2 = nums.stream().max(Comparator.naturalOrder());
OptionalInt max3 = nums.stream().mapToInt(p->p).max();
System.out.println("max1: " + max1.get() + ", max2: " 
   + max2.get() + ", max3: " + max3.getAsInt());

All of these methods, just like Collections.max, iterate over the entire collection, hence they require time proportional to the size of the collection.

bluish's user avatar

bluish

26k27 gold badges120 silver badges179 bronze badges

answered Oct 17, 2016 at 16:24

Ida Bucić's user avatar

Ida BucićIda Bucić

9398 silver badges10 bronze badges

Java 8

As integers are comparable we can use the following one liner in:

List<Integer> ints = Stream.of(22,44,11,66,33,55).collect(Collectors.toList());
Integer max = ints.stream().mapToInt(i->i).max().orElseThrow(NoSuchElementException::new); //66
Integer min = ints.stream().mapToInt(i->i).min().orElseThrow(NoSuchElementException::new); //11

Another point to note is we cannot use Funtion.identity() in place of i->i as mapToInt expects ToIntFunction which is a completely different interface and is not related to Function. Moreover this interface has only one method applyAsInt and no identity() method.

answered Sep 11, 2018 at 6:51

akhil_mittal's user avatar

akhil_mittalakhil_mittal

23k7 gold badges94 silver badges94 bronze badges

In Java8

arrayList.stream()
         .reduce(Integer::max)
         .get()

answered Jun 15, 2019 at 3:34

lasclocker's user avatar

lasclockerlasclocker

3113 silver badges8 bronze badges

Here is the fucntion

public int getIndexOfMax(ArrayList<Integer> arr){
    int MaxVal = arr.get(0); // take first as MaxVal
    int indexOfMax = -1; //returns -1 if all elements are equal
    for (int i = 0; i < arr.size(); i++) {
        //if current is less then MaxVal
        if(arr.get(i) < MaxVal ){
            MaxVal = arr.get(i); // put it in MaxVal
            indexOfMax = i; // put index of current Max
        }
    }
    return indexOfMax;  
}

answered Aug 31, 2016 at 15:47

SAM's user avatar

package in.co.largestinarraylist;

import java.util.ArrayList;
import java.util.Scanner;

public class LargestInArrayList {

    public static void main(String[] args) {

        int n;
        ArrayList<Integer> L = new ArrayList<Integer>();
        int max;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Size of Array List");
        n = in.nextInt();
        System.out.println("Enter elements in Array List");

        for (int i = 0; i < n; i++) {
            L.add(in.nextInt());
        }

        max = L.get(0);

        for (int i = 0; i < L.size(); i++) {
            if (L.get(i) > max) {
                max = L.get(i);
            }
        }

        System.out.println("Max Element: " + max);
        in.close();
    }
}

Anh Pham's user avatar

Anh Pham

2,0889 gold badges18 silver badges29 bronze badges

answered Aug 22, 2017 at 3:13

Tarun Jadhav's user avatar

In addition to gotomanners answer, in case anyone else came here looking for a null safe solution to the same problem, this is what I ended up with

Collections.max(arrayList, Comparator.nullsFirst(Comparator.naturalOrder()))

answered Feb 9, 2018 at 15:20

Chris Johansen's user avatar

model =list.stream().max(Comparator.comparing(Model::yourSortList)).get();

answered Sep 12, 2019 at 8:48

Mehmet Onar's user avatar

Mehmet OnarMehmet Onar

3492 silver badges13 bronze badges

They’re many ways to find the maximum. But there will be no noticeable difference in performance unless the collection is huge.

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);

System.out.println(
        integers.stream().max(Integer::compare).get()
);
System.out.println(
        integers.stream().mapToInt(Integer::intValue).max().getAsInt()
);
System.out.println(
        integers.stream().max(Comparator.comparing(i -> i)).get()
);
System.out.println(
        integers.stream().reduce((a, b) -> a > b ? a : b).get()
);
System.out.println(
        integers.stream().reduce(Integer.MIN_VALUE, (a, b) -> a > b ? a : b)
);

The max method expects a Comparator as a parameter.

The reduce method expects a BinaryOperator as a parameter.

answered Feb 6, 2022 at 11:48

Gayan Weerakutti's user avatar

Gayan WeerakuttiGayan Weerakutti

11.6k2 gold badges69 silver badges66 bronze badges

depending on the size of your array a multithreaded solution might also speed up things

answered Nov 29, 2011 at 1:51

niklas's user avatar

niklasniklas

3,0553 gold badges38 silver badges69 bronze badges

1

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    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

    import java.util.*;

    public class Max {

        public static void main(String args[])

        {

            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);

            int n = arr.size();

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

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

                    min = arr.get(i);

                }

            }

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

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

                    max = arr.get(i);

                }

            }

            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

    import java.util.ArrayList;

    import java.util.Collections;

    public class MinMax {

        public static void main(String args[])

        {

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

            arr.add(10);

            arr.add(20);

            arr.add(5);

            arr.add(8);

            int n = arr.size();

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

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

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

            }

            System.out.println();

            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

    import java.util.*;

    import java.util.Collections;

    public class MaxMinSort {

        public static void main(String args[])

        {

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

            arr.add(10);

            arr.add(12);

            arr.add(5);

            arr.add(8);

            arr.add(21);

            arr.add(16);

            arr.add(15);

            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();

            Collections.sort(arr);

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

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

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

            }

            System.out.println();

            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

    Last Updated :
    15 Dec, 2020

    Like Article

    Save Article

    Improve Article

    Save Article

    Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    For finding the maximum element in the ArrayList, complete traversal of the ArrayList is required. There is an inbuilt function in the ArrayList class to find the maximum element in the ArrayList, i.e. Time Complexity is O(N), where N is the size of ArrayList, Let’s discuss both the methods.

    Example:

    Input : ArrayList = {2, 9, 1, 3, 4}
    Output: Max = 9
    
    Input : ArrayList = {6, 7, 2, 1}
    Output: Max = 7

    Approach 1:

    1. Create on variable and initialize it with the first element of ArrayList.
    2. Start traversing the ArrayList.
    3. If the current element is greater than variable, then update the variable with the current element in ArrayList.
    4. In the end, print that variable.

    Below is the implementation of the above approach:

    Java

    import java.util.ArrayList;

    import java.util.Collections;

    class MinElementInArrayList {

        public static void main(String[] args)

        {

            ArrayList<Integer> myList

                = new ArrayList<Integer>();

            myList.add(16);

            myList.add(26);

            myList.add(3);

            myList.add(52);

            myList.add(70);

            myList.add(12);

            int maximum = myList.get(0);

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

                if (maximum < myList.get(i))

                    maximum = myList.get(i);

            }

            System.out.println("Maximum Element in ArrayList = "

                               + maximum);

        }

    }

    Output

    Maximum Element in ArrayList = 70
    

    Approach 2:

    The max method of the Java collection class can be used to find ArrayList. The max method returns the maximum element of the collection according to the natural ordering of the elements.

    Java

    import java.util.ArrayList;

    import java.util.Collections;

    class MinElementInArrayList {

        public static void main(String[] args)

        {

            ArrayList<Integer> myList

                = new ArrayList<Integer>();

            myList.add(16);

            myList.add(26);

            myList.add(3);

            myList.add(52);

            myList.add(70);

            myList.add(12);

            System.out.println("Maximum Element in ArrayList = "

                               + Collections.max(myList));

        }

    }

    Output

    Maximum Element in ArrayList = 70

    Last Updated :
    11 May, 2021

    Like Article

    Save Article

    Introduction

    In this guide, we’ll take a look at how to get the maximum or minimum element in a Java Collection, both for primitive types and custom comparable objects, via their fields.

    Getting the Maximum or Minimum Element with Collections.max()

    The Collections framework provides us with a wide variety of helper, static methods for working with Collections in Java. It’s no wonder that this same framework allows us to search and return the maximum or minimum element of a collection as well.

    Collections.max() and Collections.min() with Primitive Types

    Working with primitive types is fairly easy in most regards, and as long as they’re Comparable — we can easily search through them.

    To find the maximum or minimum element of a Collection consisting of primitive types, we simply call the Collections.max() or Collections.min() methods, passing in the collections we’re searching in:

    List<Integer> list = List.of(1, 5, 4, 3, 7, 6, 9, 4);
            
    Integer min = Collections.min(list);
    Integer max = Collections.max(list);
    
    System.out.println(String.format("Minimum element is %s", min));
    System.out.println(String.format("Maximum element is %s", max));
    

    Running this code returns our maximum and minimum elements:

    Minimum element is 1
    Maximum element is 9
    

    Collections.max() and Collections.min() with Custom Objects

    Though, we rarely only work with just primitive types. Typically, we’ll be working with objects. Naturally, since these structures are much more complex — you get to decide what constitutes a greater element between the two.

    Usually, this is achieved by implementing the Comparable interface, which allows you to compare any two instances of a class to determine which is greater. Let’s define a class and make it Comparable:

    public class Book implements Comparable<Book> {
        private String author;
        private String name;
        private int pageNumber;
    
        // Constructor, getters and setters
    
        @Override
        public int compareTo(Book book) {
            return (this.pageNumber > book.pageNumber) ? 1 : -1;
        }
    
        @Override
        public String toString() {
            return "Book{" +
                    "author='" + author + ''' +
                    ", name='" + name + ''' +
                    ", pageNumber=" + pageNumber +
                    '}';
        }
    }
    
    

    You’ll have to @Override the compareTo() method and define by which criteria the entities are compared with. It’ll typically boil down to simple primitive types in the end, such as comparing the pageNumber attribute. We’ve also added a toString() method for convenient formatting.

    Now, searching for the maximum or minimum element, in a collection of custom objects is as easy as calling Collections.max() or Collections.min() on the Collection:

    List<Book> bookList = new ArrayList<>();
    bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
    bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
    bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
    
    Book min = Collections.min(bookList);
    Book max = Collections.max(bookList);
    
    System.out.println(String.format("Minimum element is %s", min));
    System.out.println(String.format("Maximum element is %s", max));
    

    Given our comparison criteria, the results are:

    Minimum element is Book{author='Nick Bostrom', name='Superintelligence', pageNumber=352}
    Maximum element is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    

    Custom Comparator

    You can avoid making the Book comparable, if you can’t by supplying a new Comparator in the Collections calls. Though, this solution is verbose and best avoided/substituted with the techniques outlined after this.

    Nevertheless, it’s a fully valid way to compare entities and find the maximum/minimum value:

    Book min = Collections.min(bookList, new Comparator<Book>() {
        @Override
        public int compare(Book o1, Book o2) {
            return (o1.getPageNumber() > o2.getPageNumber()) ? 1 : -1;
        }
    });
    
    System.out.println(String.format("Minimum by page count is %s", min));
    

    Or, this can be shortened through a Lambda Expression:

    Book min = Collections.min(bookList, 
        (o1, o2) -> (o1.getPageNumber() > o2.getPageNumber()) ? 1 : -1);
    

    Getting the Maximum or Minimum Element with Stream.max() and Stream.min()

    With the advent of Java 8, we’ve been introduced to a wonderful Stream API that allows us to perform various processing pipelines. A Stream can find a maximum or minimum element via the max() or min() methods, leveraging either a new Comparator for the job, or using an already existing one, such as the comparator we’ve built-into our Book class.

    This allows you to have non-Comparable classes and quickly use a new Comparator to set the criteria using any field. This flexibility is what makes Streams so amazing for processing data.

    Stream.max() and Stream.min() with Primitive Types

    Let’s start off with a simple Collection of primitive types. To get the maximum or minimum element of the collection, we stream() it and call the min() or max() methods:

    List<Integer> list = List.of(1, 5, 4, 3, 7, 6, 9, 4);
    Integer maxInt = list.stream().mapToInt(i -> i).max().getAsInt();
    Integer minInt = list.stream().mapToInt(i -> i).min().getAsInt();
    
    System.out.println(String.format("Minimum element is %s", minInt));
    System.out.println(String.format("Maximum element is %s", maxInt));
    

    Instead of mapping i -> i, we could’ve alternatively just use:

    Integer maxInt = list.stream().mapToInt(Integer::intValue).max().getAsInt();
    

    The max() and min() methods return an Optional — or a derivative of the class, such as OptionalInt, OptionalDouble, etc. To extract the integer value — we use the getAsInt() at the end of the call chain.

    Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

    Running this code results in:

    Minimum element is 1
    Maximum element is 9
    

    Instead of mapToInt() you can also use a Comparator, such as comparing() or comparingInt() (both of which would produce the same output):

    Integer maxInt = list.stream().max(Comparator.comparing(Integer::intValue)).get();
    Integer minInt = list.stream().min(Comparator.comparingInt(Integer::intValue)).get();
    

    Again, these methods return an Optional, so we get() the result in the end. comparing() has the flexibility of comparing non-Integer values as well, but since we’re constraining ourselves to just Integers here, it doesn’t make any difference.

    Stream.max() and Stream.min() with Custom Objects

    Using custom comparators with custom objects is where Streams shine the most and where they provide the most flexibility. When using the Collections framework, we were constrained to compare the elements via the compareTo() method, overridden from the Comparable interface, if you don’t want to define a chunky new Comparator.

    With Streams — we can define a new Comparator on the fly with any field, without the class even having to implement the Comparable interface. Let’s find the maximum and minimum element of a collection with custom objects, using a custom comparator and streams:

    List<Book> bookList = new ArrayList<>();
    bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
    bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
    bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
    
    // Using native compareTo() Method
    Book min = bookList.stream().min(Book::compareTo).get();
    Book max = bookList.stream().max(Book::compareTo).get();
    
    // Using custom new Comparator
    Book minByAuthor = bookList.stream().min(Comparator.comparing(Book::getAuthor)).get();
    Book maxByAuthor = bookList.stream().max(Comparator.comparing(Book::getAuthor)).get();
    
    System.out.println(String.format("Minimum by page count is %s", min));
    System.out.println(String.format("Maximum by page count is %s", max));
    
    System.out.println(String.format("Minimum by author is %s", minByAuthor));
    System.out.println(String.format("Maximum by author is %s", maxByAuthor));
    

    This time around, we can use any field and supply it to the Comparator.comparing() method. You can also use alternative methods, such as comparingInt() here, but since we’re comparing the lexicographical value of Strings, we’ll be sticking with the generic comparing() method.

    Running this code results in:

    Minimum by page count is Book{author='Nick Bostrom', name='Superintelligence', pageNumber=352}
    Maximum by page count is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    
    Minimum by author is Book{author='Max Tegmark', name='Our Mathematical Universe', pageNumber=432}
    Maximum by author is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    

    Using a for Loop

    Finally, the good old for loop can be used to search for a maximum or minimum element:

    List<Book> bookList = new ArrayList<>();
    bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
    bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
    bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
    
    List<Integer> intList = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
    
    // Instantiate as the first book initially
    Book maxBook = bookList.get(0);
    Integer maxInt = 0;
    
    for (Book book : bookList) {
        // book.getPageNumber() < minBook.getPageNumber()
        if (book.getPageNumber() > maxBook.getPageNumber()) {
            maxBook = book;
        }
    }
    
    for (Integer integer : intList) {
        // integer < minInt
        if (integer > maxInt) {
            maxInt = integer;
        }
    }
    
    System.out.println(String.format("Maximum by page count is %s", maxBook));
    System.out.println(String.format("Maximum int is %s", maxInt));
    

    This results in the same results we’ve been seeing so far:

    Maximum by page count is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
    Maximum int is 9
    

    Conclusion

    In this guide, we’ve taken a look at how to find the maximum and minimum elements of a Java Collection. We’ve taken a look at both primitive types and custom objects, default and custom comparators, and best practices, including a manual for loop.

    A example program to find the maximum element from ArrayList. This is implemented in Java and finding max value. Finding max salary from Employee List with Collections.max().

    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.

    2. Finding the max integer value from ArrayList

    Create a list of integer values and pass the list to Collections.max(list). max() method sort the list of values in the natural order and return max value from it.

    package com.java.w3schools.blog.arraylist;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * 
     * Finding max value from list.
     * 
     * @author javaprogramto.com
     *
     */
    public class ArrayListMaxValue {
    
     public static void main(String[] args) {
    
      // creating list.
      List<Integer> intValues = new ArrayList<>();
    
      // adding values
      intValues.add(6);
      intValues.add(64);
      intValues.add(45);
      intValues.add(60);
      intValues.add(9);
      intValues.add(2);
    
      // calling max() method.
      Integer max = Collections.max(intValues);
      System.out.println("ArrayList values : " + intValues);
      System.out.println("ArrayList max value : " + max);
     }
    }
    

    Output:

    ArrayList values : [6, 64, 45, 60, 9, 2]
    ArrayList max value : 64
    

    3. Custom Objects — Find Max Salary Employee from list of Employee Objects

    • First create an employee class with id, age and salary fields.
    • Next, create a list of employee objects.
    • Last, Call Collections.sort(listOfEmps) method that should return the Employee object with max salary.
    package com.java.w3schools.blog.arraylist;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * 
     * Find employee object with max salary.
     * 
     * @author javaprogramto.com
     *
     */
    public class ArrayListCustomObjectMaxValue {
    
     public static void main(String[] args) {
    
      // creating list with type Employee.
      List<Employee> empOfList = new ArrayList<>();
    
      // adding values
      empOfList.add(new Employee(100, 45, 250000));
      empOfList.add(new Employee(109, 38, 15000));
      empOfList.add(new Employee(108, 23, 330000));
      empOfList.add(new Employee(111, 55, 873983));
      empOfList.add(new Employee(103, 25, 908022));
      empOfList.add(new Employee(102, 35, 87272));
    
      // calling max() method.
      Employee max = Collections.max(empOfList);
      System.out.println("ArrayList max value : " + max.getSalary() + " for emp id : " + max.getId());
     }
    }
    
    class Employee implements Comparable<Employee> {
    
     private int id;
     private int age;
     private long salary;
    
     public Employee(int id, int age, long salary) {
      super();
      this.id = id;
      this.age = age;
      this.salary = salary;
     }
    
     public int getId() {
      return id;
     }
    
     public int getAge() {
      return age;
     }
    
     public long getSalary() {
      return salary;
     }
    
     @Override
     public int compareTo(Employee o) {
      if (this.getSalary() > o.getSalary()) {
       return 1;
      } else if (this.getSalary() < o.getSalary()) {
       return -1;
      }
      return 0;
     }
    
    }
    

    Output:

    ArrayList max value : 908022 for emp id : 103
    

    4. Exceptions with Collections.sort()

    If the Employee class did not implement a Comparable interface then you will get compile time error as below.

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
     The method max(Collection<? extends T>) in the type Collections is not applicable for the arguments (List<Employee>)
    
     at com.java.w3schools.blog.arraylist.ArrayListCustomObjectMaxValue.main(ArrayListCustomObjectMaxValue.java:30)
    
    

    If the list is having other that Employee Objects then it will throw ClassCastException.

    If the list is empty then you will get NoSuchElementException.

    5. Conclusion

    In this article, we’ve seen how to find the max element from the list. Examples are shown for wrapper objects and custom objects in the list to find the max value.

    GitHub Code 1

    GitHub Code 2

    Reference API

    Понравилась статья? Поделить с друзьями:
  • Как самим найти воду под землей
  • Как найти число степеней свободы статистика
  • Как в приложении найди айфон найти контакты
  • Как найти базу данных postgresql
  • Как составить бюджет командировки