Find Maximum Value From ArrayList In Java - Java @ Desk

Tuesday, March 25, 2014

Find Maximum Value From ArrayList In Java

Find Maximum Value From ArrayList In Java

There are three ways to get maximum value from an ArrayList:

1) Collections.max() from java.util.Collections - Pass the arraylist object to this method and it returns the max value
2) Using Iteration
3) Using Collections.sort() from java.util.Collections - Pass the arraylist object to this method. It sorts the collection from least to maximum value. Get the value at last index from the sorted list to get maximum value

Click to see Sort ArrayList Using Comparator In Java

Sample Implementation:

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FindMaxIntegerArrayList {

 public static void main(String args[]) {
  List<Integer> integers = new ArrayList<Integer>();

  integers.add(1000);
  integers.add(895);
  integers.add(640);
  integers.add(1089);

  // Using java.util.Collections
  System.out.println("Maximum Element : " + Collections.max(integers));

  // Using Iteration
  Integer max = Integer.MIN_VALUE;
  for (Integer integer : integers) {
   if (integer > max) {
    max = integer;
   }
  }
  System.out.println("Maximum Element after iteration : " + max);

  // Using Sort Technique of java.util.Collections
  Collections.sort(integers);
  System.out.println("Maximum Element After Sorting - "
    + integers.get(integers.size() - 1));

 }
}






No comments:

Post a Comment