Java минимум и максимум

Find Max and Min in an Array in Java

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.

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

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

Sorting the array is also a good approach for small arrays. For large arrays, sorting may prove a performance issue so choose wisely.

Читайте также:  Html движение по странице

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

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

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)

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.

Читайте также:  Cache manager in java

Источник

Как найти максимальное и минимальное значения в Java?

Этот урок на 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() для вычисления минимального числа. Если наша программа правильная, то оба результата должны быть выведены одинаковыми.

Java программа для нахождения максимума и минимума чисел

Мы можем запустить эту программу из 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

Читайте также:  Positioning images in php

Из массива int

В этом примере мы находим максимальные и минимальные значения элемента из массива int на Java.

class MinMaxExample < public static void main(String args[])< int array[] = new int[]; // Вызов метода 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> 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));

Средняя оценка 3.9 / 5. Количество голосов: 64

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

Оцените статью