Created
March 29, 2025 13:41
2. Stream을 활용한 콘솔 입력 처리 프로그램
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
import java.util.NoSuchElementException; | |
import java.util.Scanner; | |
/** | |
* 변상훈 | |
* 2. Stream을 활용한 콘솔 입력 처리 프로그램 | |
*/ | |
public class StreamInputHandler { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
List<Integer> list = null; | |
while (list == null) { | |
try { | |
System.out.println("숫자를 입력하세요 (공백 또는 쉼표로 구분) :"); | |
String input = sc.nextLine(); | |
list = Arrays.stream(input.split("[ ,]+")).map(Integer::parseInt).toList(); | |
if (list.isEmpty()) { | |
System.out.println("입력이 잘못되었습니다."); | |
list = null; | |
} | |
} catch (NumberFormatException e) { | |
System.out.println("입력이 잘못되었습니다."); | |
} | |
} | |
System.out.println(); | |
System.out.println("입력된 숫자: " + list); | |
// 합계, 평균 | |
int sum = getSum(list); | |
double average = getAverage(list); | |
System.out.println("합계: " + sum); | |
System.out.println("평균: " + average); | |
// 짝수, 홀수 분류 | |
List<Integer> evenList = getEvens(list); | |
List<Integer> oddList = getOdds(list); | |
System.out.println("짝수: " + evenList); | |
System.out.println("홀수: " + oddList); | |
// 최댓값, 최솟값 | |
int max = getMax(list); | |
int min = getMin(list); | |
System.out.println("최댓값: " + max); | |
System.out.println("최솟값: " + min); | |
// 중복을 제거하고 정렬 | |
List<Integer> sortedList = sortList(list); | |
System.out.println("중복 제거 후 정렬된 숫자: " + sortedList); | |
sc.close(); | |
} | |
private static int getSum(List<Integer> list) { | |
return list.stream().reduce(0, Integer::sum); | |
} | |
private static double getAverage(List<Integer> list) { | |
return (double) getSum(list) / list.size(); | |
} | |
private static List<Integer> getEvens(List<Integer> list) { | |
return list.stream().filter(i -> i % 2 == 0).toList(); | |
} | |
private static List<Integer> getOdds(List<Integer> list) { | |
return list.stream().filter(i -> i % 2 == 1).toList(); | |
} | |
private static int getMax(List<Integer> list) { | |
return list.stream().max(Integer::compare).get(); // 입력에서 빈 리스트 비허용 | |
} | |
private static int getMin(List<Integer> list) { | |
return list.stream().min(Integer::compare).get(); // 입력에서 빈 리스트 비허용 | |
} | |
private static List<Integer> sortList(List<Integer> list) { | |
return list.stream().distinct().sorted().toList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment