- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 max and min values in an array of primitives using Java
This example shows how to search the minimum and maximum element in an array by using Collection.max() and Collection.min() methods of Collection class.
Example
import java.util.Arrays; import java.util.Collections; public class Main { public static void main(String[] args) { Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5}; int min = (int) Collections.min(Arrays.asList(numbers)); int max = (int) Collections.max(Arrays.asList(numbers)); System.out.println("Min number: " + min); System.out.println("Max number: " + max); } }
Result
The above code sample will produce the following result.
Min number: 1 Max number: 9
Another sample example of the minimum and the maximum element in an array.
Example
public class HelloWorld { public static void main(String[] args) { int numbers[] = new int[]{8, 2, 7, 1, 4, 9, 5}; int s = numbers[0]; int l = numbers[0]; for(int i = 1; i< numbers.length; i++) { if(numbers[i] > l)l = numbers[i]; else if (numbers[i] < s)s = numbers[i]; } System.out.println("Largest Number is : " + l); System.out.println("Smallest Number is : " + s); } }
The above code sample will produce the following result.
Result
Largest Number is : 9 Smallest Number is : 1
- Related Articles
- Find max and min values in array of primitives using Java
- Min and max values of an array in MongoDB?
- Get max and min values of an array in Arduino
- How to find Min/Max numbers in a java array?
- How to find the min/max element of an Array in JavaScript?
- Set min-width and max-width of an element using CSS
- Set min-height and max-height of an element using CSS
- Average of array excluding min max JavaScript
- JavaScript: How to Find Min/Max Values Without Math Functions?
- max() and min() in Python
- Sort array based on min and max date in JavaScript?
- How to calculate average without max and min values in Excel?
- Min-Max Range Queries in Array in C++
- Use of min() and max() in Python
- Explain the use of MIN() and MAX() using MySQL in Python?

Advertisements