[java] java List에서 Max, Min 값 구하기

[java] java List에서 Max, Min 값 구하기

반응형

Array에서 max,min 값을 구하는 방법을 확인해보겠습니다.

1. Integer array일 경우, Collections List로 변환 후 maptoInt().max()사용

public class StreamMaxMin { public static void main(String[] args) { Integer[] arr = {1, 2, 3, 4, 5}; List list = Arrays.asList(arr); Integer max = list.stream() .mapToInt(x -> x) .max() .getAsInt(); Integer min = list.stream() .mapToInt(x -> x) .min() .getAsInt(); System.out.println("max : " + max); System.out.println("min : " + min); } }

#출력결과

max : 5

min : 1

2.int 타입 array를 stream으로 바로 변환해서 max()사용

public static void test1() { //타입이 int일경우 int[] arr = {1, 2, 3, 4, 5}; int max = Arrays.stream(arr) .max() .getAsInt(); int min = Arrays.stream(arr) .min() .getAsInt(); System.out.println("max : " + max); System.out.println("min : " + min); }

#출력결과

max : 5

min : 1

반응형

from http://vmpo.tistory.com/122 by ccl(A) rewrite - 2021-10-04 20:26:49