Collections.max
Collections is the class of java.util package. max is the static method of Collection class. max method provides big data object from the List of Objects.
Instead of using manual algorithms, such as binary search, sequential search can get the max amount like below.
Collections.max(<ListObject>);
|
Manual Sequential search Example
import java.util.ArrayList;
import java.util.List;
public class CustomMaxExample {
public static void main(String args[]) throws Exception{
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
int maxNumber = 0;
for (int index=0;index<numbers.size();index++){
if (numbers.get(index) > maxNumber){
maxNumber = numbers.get(index);
}
}
System.out.println("Maximum is: "+maxNumber);
}
}
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GetMaxNumberJava {
public static void main(String args[]) throws Exception{
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
int maxNumber = Collections.max(numbers);
System.out.println("Maximum is: "+maxNumber);
}
}
|