ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바 2차원 배열 최댓값 구하기
    잡다한 것들 2022. 8. 21. 13:10
    반응형

    최댓값 구하기. 

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class Main {
    
        static int find_max(int[][] arrays) {
            int max = 0;
            for (var array : arrays)
                for (var element : array)
                    if (element > max) max = element;
            return max;
        }
    
        static int find_max2(int[][] arrays) {
            return Arrays.stream(arrays)
                    .map(array -> Arrays.stream(array).max().orElseThrow())
                    .max(Comparator.naturalOrder()).orElseThrow();
        }
    
        static int find_max3(int[][] arrays) {
            return Arrays.stream(arrays)
                    .flatMapToInt(Arrays::stream)
                    .max().orElseThrow();
        }
    
        public static void main(String[] args) {
            var array2d = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9, 0}};
            System.out.println(Arrays.deepToString(array2d));
            System.out.println(find_max(array2d));
            System.out.println(find_max2(array2d));
            System.out.println(find_max3(array2d));
        }
    }

     

    참고 

    https://homoefficio.github.io/2019/10/03/Java-Optional-%EB%B0%94%EB%A5%B4%EA%B2%8C-%EC%93%B0%EA%B8%B0/

     

    반응형
Designed by Tistory.