Java를 사용하여 기본 배열에서 최대 / 최소 값 찾기
배열에서 최소 / 최대 값을 결정하는 함수를 작성하는 것은 간단합니다.
/**
*
* @param chars
* @return the max value in the array of chars
*/
private static int maxValue(char[] chars) {
int max = chars[0];
for (int ktr = 0; ktr < chars.length; ktr++) {
if (chars[ktr] > max) {
max = chars[ktr];
}
}
return max;
}
그러나 이것은 이미 어딘가에서 이루어지지 않았습니까?
Commons Lang 사용 (변환) + 콜렉션 (최소 / 최대)
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 = {'3', '5', '1', '4', '2'};
List b = Arrays.asList(ArrayUtils.toObject(a));
System.out.println(Collections.min(b));
System.out.println(Collections.max(b));
}
}
Arrays.asList()
기본 배열 을 래핑하므로 메모리를 너무 많이 사용해서는 안되며 배열 요소에 대한 복사를 수행해서는 안됩니다.
당신은 단순히 새로운 자바 8 사용할 수 있습니다 Stream
들 하지만 당신과 함께 일해야한다 int
.
stream
유틸리티 클래스의 방법은 Arrays
당신에게주는 IntStream
당신이 사용할 수에 min
방법을. 당신도 할 수있는 max
, sum
, average
, ...
이 getAsInt
방법은OptionalInt
import java.util.Arrays;
public class Test {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
int min = Arrays.stream(tab).min().getAsInt();
int max = Arrays.stream(tab).max().getAsInt();
System.out.println("Min = " + min);
System.out.println("Max = " + max)
}
}
== 업데이트 ==
실행 시간이 중요하고 한 번만 데이터를 통과하려는 경우 다음 summaryStatistics()
과 같은 방법을 사용할 수 있습니다
import java.util.Arrays;
import java.util.IntSummaryStatistics;
public class SOTest {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics();
int min = stat.getMin();
int max = stat.getMax();
System.out.println("Min = " + min);
System.out.println("Max = " + max);
}
}
이 방법은 summaryStatistics
방법이 축소 연산 이고 병렬화 가 가능 하기 때문에 기존 루프보다 더 나은 성능을 제공 할 수 있습니다.
구글 구아바 라이브러리 는 등 숯을, INTS, 걷고, 클래스의 최소 및 최대 방법이있다.
따라서 다음을 간단히 사용할 수 있습니다.
Chars.min(myarray)
변환이 필요하지 않으며 아마도 효율적으로 구현됩니다.
예, Collections 클래스 에서 수행됩니다 . 프리미티브 char 배열을 Character []로 수동으로 변환해야합니다.
간단한 데모 :
import java.util.*;
public class Main {
public static Character[] convert(char[] chars) {
Character[] copy = new Character[chars.length];
for(int i = 0; i < copy.length; i++) {
copy[i] = Character.valueOf(chars[i]);
}
return copy;
}
public static void main(String[] args) {
char[] a = {'3', '5', '1', '4', '2'};
Character[] b = convert(a);
System.out.println(Collections.max(Arrays.asList(b)));
}
}
import java.util.Arrays;
public class apples {
public static void main(String[] args) {
int a[] = {2,5,3,7,8};
Arrays.sort(a);
int min =a[0];
System.out.println(min);
int max= a[a.length-1];
System.out.println(max);
}
}
다음과 같은 방법으로 모든 응용 프로그램에 작은 도우미 클래스가 있습니다.
public static double arrayMax(double[] arr) {
double max = Double.NEGATIVE_INFINITY;
for(double cur: arr)
max = Math.max(max, cur);
return max;
}
You could easily do it with an IntStream
and the max()
method.
Example
public static int maxValue(final int[] intArray) {
return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}
Explanation
range(0, intArray.length)
- To get a stream with as many elements as present in theintArray
.map(i -> intArray[i])
- Map every element of the stream to an actual element of theintArray
.max()
- Get the maximum element of this stream asOptionalInt
.getAsInt()
- Unwrap theOptionalInt
. (You could also use here:orElse(0)
, just in case theOptionalInt
is empty.)
import java.util.Random;
public class Main {
public static void main(String[] args) {
int a[] = new int [100];
Random rnd = new Random ();
for (int i = 0; i< a.length; i++) {
a[i] = rnd.nextInt(99-0)+0;
System.out.println(a[i]);
}
int max = 0;
for (int i = 0; i < a.length; i++) {
a[i] = max;
for (int j = i+1; j<a.length; j++) {
if (a[j] > max) {
max = a[j];
}
}
}
System.out.println("Max element: " + max);
}
}
public int getMin(int[] values){
int ret = values[0];
for(int i = 1; i < values.length; i++)
ret = Math.min(ret,values[i]);
return ret;
}
A solution with reduce()
:
int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97
In the code above, reduce()
returns data in Optional
format, which you can convert to int
by getAsInt()
.
If we want to compare the max value with a certain number, we can set a start value in reduce()
:
int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100
In the code above, when reduce()
with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:
double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0
Here's a utility class providing min/max
methods for primitive types: Primitives.java
Example with float:
public static float getMaxFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[data.length - 1];
}
public static float getMinFloat(float[] data) {
float[] copy = Arrays.copyOf(data, data.length);
Arrays.sort(copy);
return copy[0];
}
Here is a solution to get the max value in about 99% of runs (change the 0.01 to get a better result):
public static double getMax(double[] vals){
final double[] max = {Double.NEGATIVE_INFINITY};
IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
.forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);
return max[0];
}
(Not completely serious)
Pass the array to a method that sorts it with Arrays.sort()
so it only sorts the array the method is using then sets min to array[0]
and max to array[array.length-1]
.
The basic way to get the min/max value of an Array. If you need the unsorted array, you may create a copy or pass it to a method that returns the min or max. If not, sorted array is better since it performs faster in some cases.
public class MinMaxValueOfArray {
public static void main(String[] args) {
int[] A = {2, 4, 3, 5, 5};
Arrays.sort(A);
int min = A[0];
int max = A[A.length -1];
System.out.println("Min Value = " + min);
System.out.println("Max Value = " + max);
}
}
'development' 카테고리의 다른 글
분할 화면 emacs 창의 크기를 변경하는 방법? (0) | 2020.05.29 |
---|---|
Java에서 주기적 작업을 예약하는 방법은 무엇입니까? (0) | 2020.05.29 |
Android 에뮬레이터는 검은 색 화면 외에는 아무것도 표시하지 않으며 adb 장치는 "장치 오프라인"을 표시합니다 (0) | 2020.05.29 |
자바 다중 상속 (0) | 2020.05.29 |
Angular2 http.get (), map (), subscribe () 및 관찰 가능한 패턴-기본 이해 (0) | 2020.05.29 |