Finding the max/min value in an array of primitives using Java
Array of primitive to array of containers would help: stackoverflow.com/questions/3770289/… followed by Collections.max(Arrays.asList()) .
17 Answers 17
Using Commons Lang (to convert) + Collections (to min/max)
import java.util.Arrays; import java.util.Collections; import org.apache.commons.lang.ArrayUtils; public class MinMaxValue < public static void main(String[] args) < char[] a = ; List b = Arrays.asList(ArrayUtils.toObject(a)); System.out.println(Collections.min(b)); System.out.println(Collections.max(b)); > >
Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.
Arrays.asList() should be fine, but ArrayUtils.toObject() will copy each element of a to a new array of Character .
Arrays.asList(a) doesn’t work. You can’t make a list of primitives ( List in this case). First you need to convert the primitive values to objects and that’s why ArrayUtils.toObject is used.
You can simply use the new Java 8 Stream s but you have to work with int .
The stream method of the utility class Arrays gives you an IntStream on which you can use the min method. You can also do max , sum , average .
The getAsInt method is used to get the value from the OptionalInt
import java.util.Arrays; public class Test < public static void main(String[] args)< int[] tab = ; int min = Arrays.stream(tab).min().getAsInt(); int max = Arrays.stream(tab).max().getAsInt(); System.out.println("Min = " + min); System.out.println("Max https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#summaryStatistics--" rel="noreferrer">summaryStatistics() method like this
import java.util.Arrays; import java.util.IntSummaryStatistics; public class SOTest < public static void main(String[] args)< int[] tab = ; IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics(); int min = stat.getMin(); int max = stat.getMax(); System.out.println("Min = " + min); System.out.println("Max https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#summaryStatistics--" rel="noreferrer">summaryStatistics method is a reduction operation and it allows parallelization.
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
В Java 8 и выше можно использовать потоки streams для нахождения максимального числа в массиве. Для этого можно использовать метод max() класса java.util.stream.IntStream , который возвращает максимальное значение в потоке.
Здесь мы создаем поток из массива numbers с помощью метода Arrays.stream() , а затем вызываем метод max() для нахождения максимального значения. Метод max() вернет объект OptionalInt , поэтому мы вызываем метод getAsInt() для получения примитивного значения int
Чтобы найти максимальное число в массиве, можно использовать цикл для прохода по всем элементам и сравнения каждого элемента с текущим максимальным значением. Начальное значение максимального элемента можно установить как первый элемент массива, а затем в цикле сравнивать оставшиеся элементы с текущим максимальным значением и обновлять максимальный элемент, если текущий элемент больше. Вот как можно реализовать эту логику:
public staticintfindMax(int[]arr)intmax=arr[0];// начальное значение максимального элементаfor(inti=1;iarr.length;i++)if(arr[i]>max)max=arr[i];>>returnmax;>
Этот метод принимает в качестве аргумента массив arr и возвращает максимальный элемент в массиве. Вы можете вызвать этот метод и передать ему ваш массив для нахождения максимального значения.
Найти максимальное число в массиве итеративным способом
Найти максимальное число в массиве с помощью Stream
Найти максимальное число в массиве с помощью Arrays.sort()
Массив содержит данные аналогичного типа. Хотя вы уже можете прочитать все элементы и выполнить с ними несколько операций, в этой статье показано, как найти максимальное значение в массиве в Java.
Найти максимальное число в массиве итеративным способом
Этот метод - традиционный способ найти максимальное число из массива. Он включает итератор, который используется для просмотра каждого элемента в массиве. Ниже у нас есть массив целых чисел intArray ; Сначала мы создаем переменную maxNum и инициализируем ее первым элементом intArray .
Мы создаем расширенный цикл for, который принимает массив и возвращает каждый элемент в каждой итерации. Затем мы проверяем каждый элемент с помощью maxNum , который имеет 24, и, как только он находит число больше 24, он заменяет 24 этим числом в maxNum . Он заменит число в maxNum , пока не достигнет конца массива; в противном случае он не нашел большего числа, чем существующее значение в maxNum .
Найти максимальное число в массиве с помощью Stream
В Java 8 появился Stream API , который предоставляет несколько полезных методов. Один из них - метод Arrays.stream() , который принимает массив и возвращает последовательный поток. В нашем случае у нас есть массив типа int , и когда мы передаем его в поток, он возвращает IntStream .
Функция IntStream имеет метод max() , который помогает найти максимальное значение в потоке. Он возвращает OptionalInt , который описывает, что поток также может иметь пустые значения int .
Наконец, поскольку нам нужно максимальное число в виде int , мы будем использовать метод optionalInt.getAsInt() , который возвращает результат в виде типа int .
This is a trivial thing to do actually. There are a lot of searching algorithms for this, have you even tried something?
9 Answers 9
int maxAt = 0; for (int i = 0; i < array.length; i++) < maxAt = array[i] >array[maxAt] ? i : maxAt; >
@ifLoop, it's not fixed. The first iteration of the loop will crash with an exception (-1 out of range) . edit: I see that you've corrected that now.
It might be neatest, if you would start your loop with 1 🙂 Also you can't differentiate between empty array and one element array.
public int getIndexOfLargest( int[] array ) < if ( array == null || array.length == 0 ) return -1; // null or empty int largest = 0; for ( int i = 1; i < array.length; i++ ) < if ( array[i] >array[largest] ) largest = i; > return largest; // position of the first largest found >
I wouldn't have thought so. For the avoidance of doubt, this is what I'm suggesting (copy into IDE to format nicely!): int indexOfLargest = 0; for ( int i = 0; i < array.length; i++ ) < if ( array[i] >array[indexOfLargest] ) < indexOfLargest = i; >> . Basically the same as ifLoop's answer.
This is a nice solution if the array was already of Integer s. Sadly in many cases it's not and there isn't a pleasant way to move between the two (without external libs).
public int getIndexOfMax(int array[]) < if (array.length == 0) < return -1; // array contains no elements >int max = array[0]; int pos = 0; for(int i=1; i > return pos; >
List list = Arrays.asList(1, 3, 7, 5); IntStream.range(0, list.size()) .reduce((i, j) -> list.get(i) > list.get(j) ? i : j) .getAsInt();
Two lines code will do that in efficient way
//find the maximum value using stream API of the java 8 Integer max =Arrays.stream(numbers) .max(Integer::compare).get(); // find the index of that value int index = Arrays.asList(numbers).indexOf(max);
The most elegant solution so far but due to Java streams implementation, not very efficient. C# does a better job with the IEnumerable interface implemented by arrays.
Please find below code for the same
Integer array[] = new Integer[4]; array[0] = 1; array[1] = 3; array[2] = 7; array[3] = 5; List < Integer >numberList = Arrays.asList(array); int index_maxNumber = numberList.indexOf(Collections.max(numberList)); System.out.println(index_maxNumber);
Another functional implementation
int array[] = new int[]; int maxIndex =IntStream.range(0,array.length) .boxed() .max(Comparator.comparingInt(i -> array[i])) .map(max->array[max]) .orElse(-1);
Would do it like this (as I don't know any predefined function to get the index of highest element, only the element itself, of course you could get the index with list.indexOf(element) then, but array needs to be converted to list and 2 iterations):
maxIndex = 0; for (int i = 0; i < array.length; i++) < if (array[i] >array[maxIndex]) < maxIndex = i; >>
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.