В пакетике java.util.Collections
есть уже готовые методы на такой случай. Они так и называются: max
и min
. Остается только воспользоваться ими. Например:
ArrayList<Integer> list = new ArrayList<>();
list.add(12);
list.add(21);
list.add(111);
System.out.println(Collections.max(list));
System.out.println(Collections.min(list));
Collection.max
Collection.min
Еще вариант стандартный: занести в переменные min
и max
первый элемент списка, затем проходить в цикле и сравнивать число на итерации с числом в переменных. Если оно меньше, чем min
, то заносить его в min
. Если больше, чем max
— заносить в max
.
ArrayList<Integer> list = new ArrayList<Integer>();
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(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
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
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
For finding the maximum element in the ArrayList, complete traversal of the ArrayList is required. There is an inbuilt function in the ArrayList class to find the maximum element in the ArrayList, i.e. Time Complexity is O(N), where N is the size of ArrayList, Let’s discuss both the methods.
Example:
Input : ArrayList = {2, 9, 1, 3, 4} Output: Max = 9 Input : ArrayList = {6, 7, 2, 1} Output: Max = 7
Approach 1:
- Create on variable and initialize it with the first element of ArrayList.
- Start traversing the ArrayList.
- If the current element is greater than variable, then update the variable with the current element in ArrayList.
- In the end, print that variable.
Below is the implementation of the above approach:
Java
import
java.util.ArrayList;
import
java.util.Collections;
class
MinElementInArrayList {
public
static
void
main(String[] args)
{
ArrayList<Integer> myList
=
new
ArrayList<Integer>();
myList.add(
16
);
myList.add(
26
);
myList.add(
3
);
myList.add(
52
);
myList.add(
70
);
myList.add(
12
);
int
maximum = myList.get(
0
);
for
(
int
i =
1
; i < myList.size(); i++) {
if
(maximum < myList.get(i))
maximum = myList.get(i);
}
System.out.println(
"Maximum Element in ArrayList = "
+ maximum);
}
}
Output
Maximum Element in ArrayList = 70
Approach 2:
The max method of the Java collection class can be used to find ArrayList. The max method returns the maximum element of the collection according to the natural ordering of the elements.
Java
import
java.util.ArrayList;
import
java.util.Collections;
class
MinElementInArrayList {
public
static
void
main(String[] args)
{
ArrayList<Integer> myList
=
new
ArrayList<Integer>();
myList.add(
16
);
myList.add(
26
);
myList.add(
3
);
myList.add(
52
);
myList.add(
70
);
myList.add(
12
);
System.out.println(
"Maximum Element in ArrayList = "
+ Collections.max(myList));
}
}
Output
Maximum Element in ArrayList = 70
Last Updated :
11 May, 2021
Like Article
Save Article
Этот урок на 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));
Introduction
In this guide, we’ll take a look at how to get the maximum or minimum element in a Java Collection, both for primitive types and custom comparable objects, via their fields.
Getting the Maximum or Minimum Element with Collections.max()
The Collections
framework provides us with a wide variety of helper, static methods for working with Collections in Java. It’s no wonder that this same framework allows us to search and return the maximum or minimum element of a collection as well.
Collections.max() and Collections.min() with Primitive Types
Working with primitive types is fairly easy in most regards, and as long as they’re Comparable
— we can easily search through them.
To find the maximum or minimum element of a Collection consisting of primitive types, we simply call the Collections.max()
or Collections.min()
methods, passing in the collections we’re searching in:
List<Integer> list = List.of(1, 5, 4, 3, 7, 6, 9, 4);
Integer min = Collections.min(list);
Integer max = Collections.max(list);
System.out.println(String.format("Minimum element is %s", min));
System.out.println(String.format("Maximum element is %s", max));
Running this code returns our maximum and minimum elements:
Minimum element is 1
Maximum element is 9
Collections.max() and Collections.min() with Custom Objects
Though, we rarely only work with just primitive types. Typically, we’ll be working with objects. Naturally, since these structures are much more complex — you get to decide what constitutes a greater element between the two.
Usually, this is achieved by implementing the Comparable
interface, which allows you to compare any two instances of a class to determine which is greater. Let’s define a class and make it Comparable
:
public class Book implements Comparable<Book> {
private String author;
private String name;
private int pageNumber;
// Constructor, getters and setters
@Override
public int compareTo(Book book) {
return (this.pageNumber > book.pageNumber) ? 1 : -1;
}
@Override
public String toString() {
return "Book{" +
"author='" + author + ''' +
", name='" + name + ''' +
", pageNumber=" + pageNumber +
'}';
}
}
You’ll have to @Override
the compareTo()
method and define by which criteria the entities are compared with. It’ll typically boil down to simple primitive types in the end, such as comparing the pageNumber
attribute. We’ve also added a toString()
method for convenient formatting.
Now, searching for the maximum or minimum element, in a collection of custom objects is as easy as calling Collections.max()
or Collections.min()
on the Collection:
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
Book min = Collections.min(bookList);
Book max = Collections.max(bookList);
System.out.println(String.format("Minimum element is %s", min));
System.out.println(String.format("Maximum element is %s", max));
Given our comparison criteria, the results are:
Minimum element is Book{author='Nick Bostrom', name='Superintelligence', pageNumber=352}
Maximum element is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
Custom Comparator
You can avoid making the Book
comparable, if you can’t by supplying a new Comparator
in the Collections
calls. Though, this solution is verbose and best avoided/substituted with the techniques outlined after this.
Nevertheless, it’s a fully valid way to compare entities and find the maximum/minimum value:
Book min = Collections.min(bookList, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return (o1.getPageNumber() > o2.getPageNumber()) ? 1 : -1;
}
});
System.out.println(String.format("Minimum by page count is %s", min));
Or, this can be shortened through a Lambda Expression:
Book min = Collections.min(bookList,
(o1, o2) -> (o1.getPageNumber() > o2.getPageNumber()) ? 1 : -1);
Getting the Maximum or Minimum Element with Stream.max() and Stream.min()
With the advent of Java 8, we’ve been introduced to a wonderful Stream API that allows us to perform various processing pipelines. A Stream
can find a maximum or minimum element via the max()
or min()
methods, leveraging either a new Comparator
for the job, or using an already existing one, such as the comparator we’ve built-into our Book
class.
This allows you to have non-Comparable
classes and quickly use a new Comparator
to set the criteria using any field. This flexibility is what makes Streams so amazing for processing data.
Stream.max() and Stream.min() with Primitive Types
Let’s start off with a simple Collection of primitive types. To get the maximum or minimum element of the collection, we stream()
it and call the min()
or max()
methods:
List<Integer> list = List.of(1, 5, 4, 3, 7, 6, 9, 4);
Integer maxInt = list.stream().mapToInt(i -> i).max().getAsInt();
Integer minInt = list.stream().mapToInt(i -> i).min().getAsInt();
System.out.println(String.format("Minimum element is %s", minInt));
System.out.println(String.format("Maximum element is %s", maxInt));
Instead of mapping i -> i
, we could’ve alternatively just use:
Integer maxInt = list.stream().mapToInt(Integer::intValue).max().getAsInt();
The max()
and min()
methods return an Optional
— or a derivative of the class, such as OptionalInt
, OptionalDouble
, etc. To extract the integer value — we use the getAsInt()
at the end of the call chain.
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Running this code results in:
Minimum element is 1
Maximum element is 9
Instead of mapToInt()
you can also use a Comparator
, such as comparing()
or comparingInt()
(both of which would produce the same output):
Integer maxInt = list.stream().max(Comparator.comparing(Integer::intValue)).get();
Integer minInt = list.stream().min(Comparator.comparingInt(Integer::intValue)).get();
Again, these methods return an Optional
, so we get()
the result in the end. comparing()
has the flexibility of comparing non-Integer values as well, but since we’re constraining ourselves to just Integers here, it doesn’t make any difference.
Stream.max() and Stream.min() with Custom Objects
Using custom comparators with custom objects is where Streams shine the most and where they provide the most flexibility. When using the Collections
framework, we were constrained to compare the elements via the compareTo()
method, overridden from the Comparable
interface, if you don’t want to define a chunky new Comparator
.
With Streams — we can define a new Comparator
on the fly with any field, without the class even having to implement the Comparable
interface. Let’s find the maximum and minimum element of a collection with custom objects, using a custom comparator and streams:
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
// Using native compareTo() Method
Book min = bookList.stream().min(Book::compareTo).get();
Book max = bookList.stream().max(Book::compareTo).get();
// Using custom new Comparator
Book minByAuthor = bookList.stream().min(Comparator.comparing(Book::getAuthor)).get();
Book maxByAuthor = bookList.stream().max(Comparator.comparing(Book::getAuthor)).get();
System.out.println(String.format("Minimum by page count is %s", min));
System.out.println(String.format("Maximum by page count is %s", max));
System.out.println(String.format("Minimum by author is %s", minByAuthor));
System.out.println(String.format("Maximum by author is %s", maxByAuthor));
This time around, we can use any field and supply it to the Comparator.comparing()
method. You can also use alternative methods, such as comparingInt()
here, but since we’re comparing the lexicographical value of String
s, we’ll be sticking with the generic comparing()
method.
Running this code results in:
Minimum by page count is Book{author='Nick Bostrom', name='Superintelligence', pageNumber=352}
Maximum by page count is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
Minimum by author is Book{author='Max Tegmark', name='Our Mathematical Universe', pageNumber=432}
Maximum by author is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
Using a for Loop
Finally, the good old for
loop can be used to search for a maximum or minimum element:
List<Book> bookList = new ArrayList<>();
bookList.add(new Book("Nick Bostrom", "Superintelligence", 352));
bookList.add(new Book("Ray Kurzweil", "The Singularity is Near", 652));
bookList.add(new Book("Max Tegmark", "Our Mathematical Universe", 432));
List<Integer> intList = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
// Instantiate as the first book initially
Book maxBook = bookList.get(0);
Integer maxInt = 0;
for (Book book : bookList) {
// book.getPageNumber() < minBook.getPageNumber()
if (book.getPageNumber() > maxBook.getPageNumber()) {
maxBook = book;
}
}
for (Integer integer : intList) {
// integer < minInt
if (integer > maxInt) {
maxInt = integer;
}
}
System.out.println(String.format("Maximum by page count is %s", maxBook));
System.out.println(String.format("Maximum int is %s", maxInt));
This results in the same results we’ve been seeing so far:
Maximum by page count is Book{author='Ray Kurzweil', name='The Singularity is Near', pageNumber=652}
Maximum int is 9
Conclusion
In this guide, we’ve taken a look at how to find the maximum and minimum elements of a Java Collection. We’ve taken a look at both primitive types and custom objects, default and custom comparators, and best practices, including a manual for
loop.