2026.03.06
소요 시간: 17분
문제를 풀기 전 알고리즘을 어떻게 짜야 할지 머리로 생각하고
AI 제미나이를 이용해서 구현에 도움을 받음
import java.util.IntSummaryStatistics; import java.util.Arrays; class Solution { public String solution(String s) { String answer = ""; IntSummaryStatistics stats = Arrays.stream(s.split(" ")).mapToInt(Integer::parseInt).summaryStatistics(); int min = stats.getMin(); int max = stats.getMax(); answer = Integer.toString(min) + " " + Integer.toString(max); return answer; } }
stream
데이터의 흐름을 관리하는 아주 강력한 자바의 도구
특징
최종 연산이 호출되기 전 까지 아무것도 하지 않음
중간 연산(filter,map등)을 아무리 많이 연결해도
forEach,toArray,collect같은 최종 결과물을 요구하는 연산이 들어오기 전까지는 데이터가 흐르지 않음종류
데이터를 다루는 목적에 따라 크게 두 종류로 나뉨
- 참조형 스트림(Stream): 객체(String, List, User 클래스 등)을 다룸
- 기본형 특화 스트림(
IntStream,LongStream,DoubleStream):
int,long,double을 다룸
성능 면에서 훨씬 우수하며sum(),average(),min(),max()같은 수학적 통계 메서드를 바로 쓸 수 있음주요 메서드 유형별 분류
- 중간 연산(Intermediate Operations)
데이터를 변환하거나 걸러냄:filter,map,flatMap,sorted,distinct,peek,limit,skip
특징: 결과를 리턴하는 것이 아닌, 새로운 스트림을 리턴함. 따라서 계속xxx(),xxx()형태로 이어 붙일 수 있음
- 최종 연산(Terminal Operations)
결과를 도출함:forEach,toArray,collect,reduce,anyMatch,allMatch,noneMatch,findFirst,findAny,count
특징: 스트림이 닫히고 계산이 시작됨. 이후에는 다시 사용할 수 없음예제 코드
filterList<String> fruits = Arrays.asList("apple", "banana", "cherry", "date"); List<String> result = fruits.stream() .filter(s -> s.length() >= 5) // 1. 5글자 이상만 남김 .map(String::toUpperCase) // 2. 대문자로 변환 .collect(Collectors.toList()); // 3. 리스트로 수집 // 결과: ["APPLE", "BANANA", "CHERRY"]
mapList<User> users = ...; // User 객체들이 담긴 리스트 List<String> names = users.stream() .map(User::getName) // 1. 객체에서 이름만 추출 .collect(Collectors.toList()); // 2. 이름 리스트 생성
collectList<Integer> scores = Arrays.asList(90, 45, 75, 30, 85); Map<String, List<Integer>> grouped = scores.stream() .collect(Collectors.groupingBy(s -> s >= 60 ? "PASS" : "FAIL")); // 결과: {PASS=[90, 75, 85], FAIL=[45, 30]}
distinctint[] nums = {3, 1, 4, 3, 2, 1, 5}; int[] sortedDistinct = Arrays.stream(nums) .distinct() // 1. 중복 제거 .sorted() // 2. 오름차순 정렬 .map(n -> -n) // 3. 내림차순을 위한 임시 변환 .sorted() // 4. 다시 정렬 .map(n -> -n) // 5. 원래대로 복구 .toArray();
anyMatch,allMatchList<Integer> numbers = Arrays.asList(1, 3, 5, 8); boolean hasEven = numbers.stream() .anyMatch(n -> n % 2 == 0); // 짝수가 하나라도 있는가? (true) boolean allPositive = numbers.stream() .allMatch(n -> n > 0); // 모두 양수인가? (true)
실무/알고리즘 꿀팁
IntSummaryStatistics
데이터를 딱 한번만 훑으면서 모든 정보를 다 뽑아냄IntSummaryStatistics stats = Arrays.stream(numbers) .summaryStatistics(); // 아래 값들을 한 번의 순회로 모두 구할 수 있습니다! stats.getMin(); stats.getMax(); stats.getSum(); stats.getAverage(); stats.getCount();