일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- R
- AI
- 패캠챌린지
- 패스트캠퍼스후기
- albert
- 한번에 끝내는 Java/Spring 웹 개발 마스터 초격차 패키지 Online.
- 한번에 끝내는 Java/Spring 웹 개발 마스터 초격차 패키지 Online
- 알버트
- 한번에끝내는Java/Spring웹개발마스터초격차패키지
- SKT
- 한번에 끝내는 Java/Spring 웹 개발 마스터 초격차 패키지
- 패스트캠퍼스
- 직장인자기계발
- 직장인인강
- Today
- Total
제주 탈출 일지
패스트캠퍼스 챌린지 30일차 본문
와! 챌린지 마지막 날. 여기까지 달려온 나에게 Cheers~
06. 연산 수행에 대한 구현을 할 수 있는 reduce() 연산
reduce() 연산
여러 Stream에 대해 연산이 가능한데, 정의된 연산이 아닌 프로그래머가 직접 구현한 연산을 적용하는 것.
T reduce(T identify, BinaryOperator<T> acculator)
BinaryOperator Interface를 구현한 부분인 acculator는 람다식으로 구현이 가능하다.
첫 번째 파라미터인 identify는 기본값(초기값)을 의미한다.
package ch06;
import java.util.Arrays;
import java.util.function.BinaryOperator;
class CompareString implements BinaryOperator<String> {
@Override
public String apply(String s1, String s2) {
if ( s1.getBytes().length >= s2.getBytes().length ) return s1;
else return s2;
}
}
public class ReduceTest {
public static void main(String[] args) {
String greetings[] = {"안녕하세요~~~", "hello", "Good morning", "반갑습니다.^^"};
System.out.println(Arrays.stream(greetings).reduce("", (s1, s2) ->
{ if ( s1.getBytes().length >= s2.getBytes().length ) return s1;
else return s2; }
));
// reduce( 객체 ).get();
String str = Arrays.stream(greetings).reduce(new CompareString()).get();
System.out.println(str);
}
}
람다식이 너무 길다면 BinaryOperator를 구현한 클래스를 만들고, 그 객체를 reduce안에 넣으면 apply부분이 자동으로 호출이 되어 사용된다.
이 정도까지 알면 Stream에 대한 부분은 기본적인 부분에 대해서 알고 있는 것이라고 할 수있다.
07. 스트림을 활용하여 패키지 여행 비용 계산하기
문제 정의
1. 고객의 명단을 출력
2. 여행의 총 비용을 계산
3. 고객 중 20세 이상의 사람의 이름을 정렬하여 출력.
TravelCustomer 클래스
package ch07;
public class TravelCustomer {
private String name;
private int age;
private int price;
public TravelCustomer(String name, int age, int price) {
this.age = age;
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString() {
return "name: " + name + " age: " + age + " price: " + price;
}
}
TravelCustomerTest 클래스
package ch07;
import java.util.ArrayList;
import java.util.List;
public class TravelCustomerTest {
public static void main(String[] args) {
TravelCustomer customerLee = new TravelCustomer("이순신", 40, 100);
TravelCustomer customerKim = new TravelCustomer("김유신", 20, 100);
TravelCustomer customerHong = new TravelCustomer("홍길동", 13, 50);
List<TravelCustomer> customerList = new ArrayList<TravelCustomer>();
customerList.add(customerLee);
customerList.add(customerKim);
customerList.add(customerHong);
System.out.println("고객 명단 출력");
customerList.stream().map(c->c.getName()).forEach(s->System.out.println(s));
System.out.println("여행 비용");
System.out.println(customerList.stream().mapToInt(c->c.getPrice()).sum());
System.out.println("20세 이상 고객이름 정렬");
customerList.stream().filter(c->c.getAge() >= 20).map(c->c.getName()).sorted().forEach(s->System.out.println(s));
}
}
1,2,3번의 요구사항이 구현되어 있다.
map, mapToInt, forEach, sorted, sum 과 같은 다양한 Stream 관련 메소드들이 사용되었다.
내일 다시 한번 보면 쉽지 않을듯.?
실행결과는 위와 같이 나오게 된다.
08. 예외 처리는 왜 해야 하나? 자바에서 제공되는 클래스들
파일입출력, 네트워크 커넥션, DB 커넥션에 있어서 예외 처리는 반드시 필요하다.
시스템이 죽지 않기 위해 예외 처리를 해야 한다. ( 프로그램의 비정상 종료를 피해야 한다. )
개발자가 생각하지 않은 다양한 버그 상황이 존재.
-> 로그를 남겨야 한다.( 재현이 어렵기 떄문에 어떤 상황이었는가 확인함. )
그 원인을 파악하여 bug를 수정하는 것이 중요하다.
회사마다 로그에 대한 포맷이 존재한다.
오류와 예외 클래스
Error : 가상 머신에서 발생, 프로그래머가 처리 할 수 없는 오류
ex ) 동적 메모리가 없는 경우, 스택 메모리 오버플로우
Exception : 프로그램에서 제어 할 수 있는 오류
읽어들이려는 파일이 존재하지 않거나, 네트웍이나 DB연결이 안되는 경우등
throwable 하위 클래스 error, exception.
Arithmetic Exception, NullPointerException 정도는 RuntimeException에 포함되기 때문에 알아두면 될듯하다.
이외의 다른 Exception은 IDE가 굉장히 잘 잡아준다.
챌린지 끝~~~~
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr
'패스트캠퍼스 챌린지!' 카테고리의 다른 글
패스트캠퍼스 챌린지 최종 후기 (0) | 2021.10.14 |
---|---|
패스트캠퍼스 챌린지 29일차 (0) | 2021.10.04 |
패스트캠퍼스 챌린지 28일차 (0) | 2021.10.03 |
패스트캠퍼스 챌린지 27일차 (0) | 2021.10.02 |
패스트캠퍼스 챌린지 26일차 (0) | 2021.10.01 |