Этот урок на Java для начинающих заключается в написании Java-программы, которая принимает данные от пользователя, находит максимальное и минимальное число и выводит их на консоль.
Цель этой статьи – научить получать данные от пользователя и использовать класс java.lang.Math для выполнения некоторых математических операций, например, чтобы найти максимальное и минимальное значения в Java.
Также есть другие 4 способа, которые с примерами кода даны ниже.
Мы можем использовать класс Scanner, добавленный в Java 1.5, для чтения пользовательского ввода с консоли. Сканеру нужен InputStream для чтения данных, и поскольку мы читаем с консоли, мы можем передать System.in, который является InputStream для консоли Eclipse, или командную строку в зависимости от того, что используется.
Этот класс также помогает преобразовать пользовательский ввод в требуемый тип данных, например если пользователь вводит числа, необходимо затем преобразовать их в тип данных int и сохранить их в переменной int. Можно использовать метод nextInt(), чтобы считать пользовательский ввод как Integer.
Точно так же можно использовать nextLine() для чтения ввода пользователя как String. Есть другие методы, доступные для чтения с плавающей точкой, двойного или логического значения из командной строки.
Как только получены оба числа, просто нужно использовать оператор отношения меньше и больше, чтобы найти наименьшее и наибольшее число.
После этого можно использовать Math.max(), чтобы узнать максимум двух чисел, он должен совпадать с предыдущим результатом.
Максимум и минимум на примере
Пример программы состоит из двух частей. В первой части мы принимаем данные от пользователя, используем if block и реляционный оператор, чтобы найти максимальное значение в Java, и далее используем метод Math.max() для той же цели.
Во второй части программы мы попросим пользователя ввести еще два числа, а затем мы используем if блок, чтобы вычислить меньшее из двух. После этого мы снова используем функцию Math.min() для вычисления минимального числа. Если наша программа правильная, то оба результата должны быть выведены одинаковыми.
Мы можем запустить эту программу из Eclipse IDE, просто скопировав код после создания проекта. Eclipse автоматически создаст исходный файл с тем же именем, что и открытый класс, и поместит его в нужный пакет. Кроме того, также можно запустить эту программу из командной строки, следуя приведенным здесь шагам.
import java.util.Scanner; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MaxMinExerciseInJava { public static void main(String args[]) throws InterruptedException { Scanner scnr = new Scanner(System.in); // вычисляем максимум 2 чисел System.out.println("Введите 2 числа"); int a = scnr.nextInt(); int b = scnr.nextInt(); if (a > b) { System.out.printf("Between %d and %d, maximum is %d %n", a, b, a); } else { System.out.printf("Between %d and %d, maximum number is %d %n", a, b, b); } int max = Math.max(a, b); System.out.printf("Maximum value of %d and %d using Math.max() is %d %n", a, b, max); int x = scnr.nextInt(); int y = scnr.nextInt(); if (x < y) { System.out.printf("Between %d and %d, Minimum Number is %d %n", x, y, x); } else { System.out.printf("Between %d and %d, Minimum is %d %n", x, y, y); } int min = Math.min(x, y); System.out.printf("Maximum value of %d and %d using Math.min() is %d %n", x, y, min) } }
Вывод:
введите 2 числа
10
11
Between 10 and 11, maximum number is 11
Maximum value of 10 and 11 using Math.max() is 11
Please enter two numbers to find minimum of two
45
32
Between 45 and 32, Minimum is 32
Maximum value of 45 and 32 using Math.min() is 32
Из массива int
В этом примере мы находим максимальные и минимальные значения элемента из массива int на Java.
Читайте также как найти сумму и среднее значение элементов массива на Java
class MinMaxExample { public static void main(String args[]){ int array[] = new int[]{10, 11, 88, 2, 12, 120}; // Вызов метода getMax () для получения максимального значения int max = getMax(array); System.out.println("Maximum Value is: "+max); // Вызов метода getMin () для получения минимального значения int min = getMin(array); System.out.println("Minimum Value is: "+min); } //здесь находим максимум public static int getMax(int[] inputArray){ int maxValue = inputArray[0]; for(int i=1;i < inputArray.length;i++){ if(inputArray[i] > maxValue){ maxValue = inputArray[i]; } } return maxValue; } // здесь находим минимум public static int getMin(int[] inputArray){ int minValue = inputArray[0]; for(int i=1;i<inputArray.length;i++){ if(inputArray[i] < minValue){ minValue = inputArray[i]; } } return minValue; } }
Вывод:
Maximum Value is: 120
Minimum Value is: 2
Методы max и min
В пакете java.util.Collections есть методы max и min.
ArrayList list = new ArrayList<>(); list.add(12); list.add(21); list.add(111); System.out.println(Collections.max(list)); System.out.println(Collections.min(list));
Используя цикл
Вносим в переменные min и max первый элемент из списка, запускаем цикл и сравниваем число на итерации с числом в переменных.
Если оно меньше, чем min, то присваиваем его min, иначе если больше, чем max — то это max.
ArrayList list = new ArrayList(); list.add(100); list.add(-666); list.add(666); int min = list.get(0); int max = list.get(0); for (Integer i: list) { if(i < min) min = i; if(i > max) max = i; } System.out.println("минимальное число: " + min); System.out.println("максимальное число: " + max);
С помощью Collections.sort взять первый и последний из списка
Отсортируем список с помощью Collections.sort, теперь в этом списке первый элемент – это maximum,а последний будет minimum:
Collections.sort(list); System.out.println(list.get(0)); System.out.println(list.get(list.size() - 1));
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Java as a whole is a language that generally requires a lot of coding to execute specific tasks. Hence, having shorthand for several utilities can be beneficial. One such utility, to find maximum and minimum element in array is explained in this article using “aslist()“. aslist() type casts a list from the array passed in its argument. This function is defined in “Java.utils.Arrays“.
To get the minimum or maximum value from the array we can use the Collections.min() and Collections.max() methods.
But as this method requires a list type of data we need to convert the array to list first using above explained “aslist()” function.
Note: “The array you are passing to the Arrays.asList() must have a return type of Integer or whatever class you want to use”, since the Collections.sort() accepts ArrayList object as a parameter.
Note: If you use type int while declaring the array you will end up seeing this error: “no suitable method found for min(List<int[]>)”
Java
import
java.util.Arrays;
import
java.util.Collections;
public
class
MinNMax {
public
static
void
main(String[] args)
{
Integer[] num = {
2
,
4
,
7
,
5
,
9
};
int
min = Collections.min(Arrays.asList(num));
int
max = Collections.max(Arrays.asList(num));
System.out.println(
"Minimum number of array is : "
+ min);
System.out.println(
"Maximum number of array is : "
+ max);
}
}
Output
Minimum number of array is : 2 Maximum number of array is : 9
This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Last Updated :
21 Jun, 2022
Like Article
Save Article
Improve Article
Save Article
Like Article
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
- First, we need to initialize the ArrayList values.
- Then the length of the ArrayList can be found by using the size() function.
- After that, the first element of the ArrayList will be store in the variable min and max.
- 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:
- First, we need to create a class.
- 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.
- The length of the ArrayList will be used to iterate through the loop and print the elements of the ArrayList.
- 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
- 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.
- After that, the ArrayList of integers will be created and then we will calculate the length using size() function.
- Then, the ArrayList will be sorted using the predefined function, and by default, it will be sorted in increasing order only.
- 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.
- 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.
- 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
В Java 8
и выше можно использовать потоки streams
для нахождения минимального числа в массиве. Для этого можно использовать метод min()
класса java.util.stream.IntStream
, который возвращает минимальное значение в потоке.
Пример:
int[] numbers = {10, 20, 30, 40, 50};
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("Минимальное число: " + min);
Результат:
Минимальное число: 10
Здесь мы создаем поток из массива numbers
с помощью метода Arrays.stream()
, а затем вызываем метод min()
для нахождения минимального значения.
Метод min()
вернет объект OptionalInt
, поэтому мы вызываем метод getAsInt()
для получения примитивного значения int
Learn to find the smallest and the largest item in an array in Java. We will discuss different approaches from simple iterations to the Stream APIs.
In the given examples, we are taking an array of int values. We can apply all the given solutions to an array of objects or custom classes as well. In the case of custom objects, we only need to override the equals() method and provide the correct logic to compare two instances.
int[] items = { 10, 0, 30, 2, 7, 5, 90, 76, 100, 45, 55 }; // Min = 0, Max = 100
1. Find Max/Min using Stream API
Java streams provide a lot of useful classes and methods for performing aggregate operations. Let’s discuss a few of them.
1.1. Stream.max() and Stream.min()
The Stream
interface provides two methods max()
and min()
that return the largest and the smallest item from the underlying stream.
Both methods can take a custom Comparator
instance if we want a custom comparison logic between the items.
For primitives, we have IntStream
, LongStream
and DoubleStream
to support sequential and parallel aggregate operations on the stream items. We can use the java.util.Arrays.stream()
method to convert the array to Stream and then perform any kind of operation on it.
int max = Arrays.stream(items)
.max()
.getAsInt(); // 100
int min = Arrays.stream(items)
.min()
.getAsInt(); // 0
1.2. IntStream.summaryStatistics()
In the above example, we find the array’s max and min items in two separate steps. We are creating the stream two times and operating on it two times. This is useful when we only have to find either the maximum item or the minimum item.
If we have to find the max and min item both then getting the max and min item from the array in a single iteration makes complete sense. We can do it using the IntSummaryStatistics
instance. A similar instance is available for LongStream and DoubleStream as well.
IntSummaryStatistics stats = Arrays.stream(items).summaryStatistics();
stats.getMax(); //100
stats.getMin(); //0
2. Collections.min() and Collections.max()
The Collections
class provides the aggregate operations for items in a collection such as List. We can convert an array into a List and use these APIs to find the max and min items.
In the given example, we are converting the int[] to Integer[]. If you have an Object[] already then you can directly pass the array to Arrays.asList()
API.
Integer min = Collections.min(Arrays.asList(ArrayUtils.toObject(items)));
Integer max = Collections.max(Arrays.asList(ArrayUtils.toObject(items)));
3. Sorting the Array
Sorting the array is also a good approach for small arrays. For large arrays, sorting may prove a performance issue so choose wisely.
In a sorted array, the min and max items will be at the start and the end of the array.
Arrays.sort(items);
max = items[items.length - 1]; //100
min = items[0]; //0
4. Iterating the Array
This is the most basic version of the solution. The pseudo-code is :
Initialize the max and min with first item in the array Iterate the array from second position (index 1) Compare the ith item with max and min if current item is greater than max set max = current item elseif current item is lower than min set min = current item
After the loop finishes, the max
and min
variable will be referencing the largest and the smallest item in the array.
max = items[0];
min = items[0];
for (int i = 1; i < items.length; i++) {
if (items[i] > max) {
max = items[i];
}
else if (items[i] < min) {
min = items[i];
}
}
System.out.println(max); //100
System.out.println(min); //0
5. Recursion
Recursion gives better performance for a big-size unsorted array. Note that we are writing the recursive call for max and min items, separately. If we need to find both items in a single invocation, we will need to change the program as per demand.
This solution is basically Divide and Conquer algorithm where we only handle the current index and the result of the rest (the recursive call) and merge them together for the final output.
For getting the maximum of items, at each item, we return the larger of the current items in comparison and all of the items with a greater index. A similar approach is for finding the minimum item.
min = getMax(items, 0, items[0]); //0
min = getMin(items, 0, items[0]); //100
public static int getMax(final int[] numbers, final int a, final int n) {
return a >= numbers.length ? n
: Math.max(n, getMax(numbers, a + 1, numbers[a] > n ? numbers[a] : n));
}
private static int getMin(final int[] numbers, final int a, final int n) {
return a == numbers.length ? n
: Math.min(n, getMin(numbers, a + 1, numbers[a] < n ? numbers[a] : n));
}
6. Conclusion
In this short Java tutorial, we learned the different ways to find the maximum and the minimum element from an Array in Java. We learned to use the Stream API, Collections API, simple iterations, and advanced techniques such as recursion.
For smaller arrays, we should prefer the code readability and use the Stream or Collection APIs. For large arrays, where we will get noticeable performance improvements, using recursion can be considered.
Happy Learning !!
Sourcecode on Github