[Java] 스트림(Stream) 최댓값 찾기

서재·2023년 9월 26일

[Java] 스트림(Stream)

목록 보기
2/4

✅ 목표

List<Integer> 로부터 최댓값 탐색


📕 without Stream

int maxValue = list.get(0);

for (int value : list) {
    maxValue = Math.max(maxValue, value);
}

📘 with Stream

int maxValue = list.stream()
        .max(Comparator.comparingInt(e -> e))	// .map((e1, e2) -> e1 - e2)
        .get();
int maxValue = list.stream()
        .max(Comparator.comparingInt(e -> e))	// .map((e1, e2) -> e1 - e2)
        .orElse(-1);

📌 .max(Comparator)

비교 연산에 따라 최댓값을 추출
Optional 객체를 반환

📌 .get()

Optional 객체로부터 값을 읽어오는 메소드
값이 없다면 예외가 발생할 수 있음

📌 .orElse()

Optional 객체에 값이 없을 경우 기본 값을 설정

profile
입니다.

0개의 댓글