[개발] - Java/후발대
후발대 18일차 전체 코드
완벽한 장면
2023. 2. 21. 01:05
후발대수업_18.
스트림 (Stream) map, 예외처리 (TryCatch, Catch) , + 스트림 퀴즈, 2주차 과제 샘플 답안,
스트림은 한번 사용하고 나면은 다시 사용 할 수 없기 때문에, 매번 새롭게 만들어야 하는것.
또한 스트림을 쓴다고 해서 원본데이터가 변경되거나 훼손되는 것은 아님.
항상 stream을 만들때마다 원본 데이터로 만들기 때문에 전체 데이터를 가지고 새롭게 작업할 수 있으니
스트림은 마음껏 쓰셔도 괜찮다.
진행 내용 (수업자료)
실습코드
Stream(2)
package com.sparta.hbd04.prac01.prac15;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class _05_Stream {
public static void main(String[] args) {
// 스트림 -> 스트림 생성
// Arrays.stream
int[] scores = {100, 95, 90, 85, 80};
IntStream scoreStream = Arrays.stream(scores);
String[] langs = {"python", "java", "javascript", "c", "c++", "c#"};
// Stream<String> stream = Arrays.stream(langs);
Stream<String> langStream = Arrays.stream(langs);
// Collections.stream()
List<String> langList = new ArrayList<>();
// langList.add("python");
// langList.add("java");
langList = Arrays.asList("python", "java", "javascript", "c", "c++", "c#");
// System.out.println(langList.size());
Stream<String> langListStream = langList.stream();
// Stream.of()
Stream<String> langListOfStream = Stream.of("python", "java", "javascript", "c", "c++", "c#");
// 스트림 사용
// 중간 연산 (Intermediate Operation) : filter, map, sorted, distict, skip, ...
// 최종 연산 (Terminal Operation) : count, min, max, sum, forEach, anyMatch, allMatch, ...
// 90점 이상인 점수만 출력
Arrays.stream(scores).filter(x -> x >= 90).forEach(x -> System.out.println(x));
System.out.println("-------------");
// Arrays.stream(scores).filter(x -> x >= 90).forEach(System.out::println);
// 90점 이상인 사람의 수
int count = (int) Arrays.stream(scores).filter(x -> x >= 90).count();
System.out.println(count);
System.out.println("------------");
// 90 점 이상인 점수들의 합
int sum = Arrays.stream(scores).filter(x -> x >= 90).sum();
System.out.println(sum);
System.out.println("---------------");
// 90점 이상인 점수들을 정렬
Arrays.stream(scores).filter(x -> x >= 90).sorted().forEach(System.out::println);
System.out.println("-----------------");
// "python", "java", "javascript", "c", "c++", "c#"
// c로 시작하는 프로그래밍 언어
Arrays.stream(langs).filter(x -> x.startsWith("c")).forEach(System.out::println);
System.out.println("----------------");
// java 라는 언어를 포함하는 언어
Arrays.stream(langs).filter(x -> x.contains("java")).forEach(System.out::println);
System.out.println("----------");
// 4글자 이하의 언어를 정렬해서 출력 (리스트를 사용)
langList.stream().filter(x -> x.length() <= 4).sorted().forEach(System.out::println);
System.out.println("-------------");
// 4글자 이하의 언어 중에서 c라는 글자를 포함하는 언어
langList.stream()
.filter(x -> x.length() <= 4)
.filter(x -> x.contains("c"))
.forEach(System.out::println);
System.out.println("------------");
// 4글자 이하의 언어 중에서 c라는 글자를 포함하는 언어가 하나라도 있는지 여부
Boolean anymatch = langList.stream()
.filter(x -> x.length() <= 4)
.anyMatch(x -> x.contains("c"));
System.out.println(anymatch);
System.out.println("-------------------");
// 4글자 이하의 언어들은 모두 c 라는 글자를 포함하는지 여부
boolean allmatch = langList.stream()
.filter(x -> x.length() <= 4) //3 으로 변경 하면 True
.allMatch(x -> x.contains("c"));
System.out.println(allmatch);
System.out.println("-------------------");
// 4글자 이하의 언어 중에서 c 라는 글자를 포함하는 언어 뒤에 (어려워요) 라는 글자를 함께 출력
//map
langList.stream()
.filter(x -> x.length() <= 4)
.filter(x -> x.contains("c"))
.map(x -> x + "(어려워요)")
.forEach(System.out::println);
System.out.println("---------------------");
// c라는 글자를 포함하는 언어를 대문자로 출력
langList.stream()
.filter(x -> x.contains("c"))
.map(String::toUpperCase)
.forEach(System.out::println);
System.out.println("--------------------");
// c 라는 글자를 포함하는 언어를 대문자로 변경하여 리스트로 저장
List<String> langLstStartsWithC = langList.stream()
.filter(x -> x.contains("c"))
.map(String::toUpperCase)
.collect(Collectors.toList());
langLstStartsWithC.stream().forEach(System.out::println);
}
}
_01_TryCatch
package com.sparta.hbd04.prac01.prac19;
public class _01_TryCatch {
public static void main(String[] args) {
// 예외 처리:
// 오류 : 컴파일 오류, 런타임 오류 (에러 error, 예외 exception)
// int i = "문자열";
// int[] arr = new int[3];
// arr[5] = 100;
// S s = new S();
// s.methodA();
try {
// System.out.println(3 / 0);
// int[] arr = new int[3];
// arr[5] = 100;
Object obj = "test";
System.out.println((int) obj);
} catch (Exception e) {
System.out.println("이런 문제가 발생했어요 => " + e.getMessage());
e.printStackTrace();
}
System.out.println("프로그램 정상 종료");
}
}
//class S {
// public void methodA() {
// this.methodA();
// }
//}
02_Catch
package com.sparta.hbd04.prac01.prac19;
public class _02_Catch {
public static void main(String[] args) {
/*
// catch 괄호 안의 Exception 클래스는 최고 조상 클래스라는 것을 잘 알아두자
// 그 말은, 원래 예외처리는 다양한 형태로 이루어질 수 있다는 뜻이지
// 아까 했던 예시 1)
try {
System.out.println(3/0);
} catch (ArithmeticException e) {
System.out.println("뭔가 잘못 계산하셨네요.");
// 지금 상황에서는 여기서 끝. 아래로 안 넘어간다
} catch (Exception e) {
System.out.println("이런 문제가 발생했어요 => " + e.getMessage());
e.printStackTrace();
}
System.out.println("프로그램 정상 종료");
}
*/
/*
// 아까 했던 예시 2)
try {
int[] arr = new int[3];
arr[5] = 100;
} catch (ArithmeticException e) {
System.out.println("뭔가 잘못 계산하셨네요."); // 이건 건너뜀
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("인덱스를 잘못 설정했어요."); // 여기서 처리된다.
} catch (Exception e) {
System.out.println("이런 문제가 발생했어요 => " + e.getMessage());
e.printStackTrace();
}
System.out.println("프로그램 정상 종료");
*/
// 아까 했던 예시 3
try {
Object obj = "test";
System.out.println((int)obj);
} catch (ArithmeticException e) {
System.out.println("뭔가 잘못 계산하셨네요."); // 이건 건너뜀
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("인덱스를 잘못 설정했어요."); // 이것도 건너뜀.
} catch (ClassCastException e) {
System.out.println("잘못된 형 변환입니다."); // 여기서 처리
} catch (Exception e) {
System.out.println("이런 문제가 발생했어요 => " + e.getMessage());
e.printStackTrace();
}
System.out.println("프로그램 정상 종료");
}
}
728x90
반응형