컴퓨터공학 💻 도서관📚
Part2. 6-7 스트림을 활용하여 패키지 여행 비용 계산하기 본문
문제 정의
// 요런 문제에 스트림을 활용하면 좋다는 예시
여행사에 패키지 여행 상품이 있습니다. 여행 비용은 15세 이상은 100만원, 그 미만은 50만원 입니다.
고객 세 명이 패키지 여행을 떠난다고 했을 때 비용 계산과 고객 명단 검색등에 대한 연산을 스트림을 활용하여 구현해 봅니다.
고객에 대한 클래스를 만들고 ArrayList로 고객을 관리 합니다.
고객 정보는 다음과 같습니다.
CustomerLee
이름 : 이순신
나이 : 40
비용 : 100
CustomerKim
이름 : 김유신
나이 : 20
비용 : 100
CustomerHong
이름 : 홍길동
나이 :13
비용 : 50
고객 클래스
public class TravelCustomer {
private String name; //이름
private int age; //나이
private int price; //가격
public TravelCustomer(String name, int age, int price) {
this.name = name;
this.age = age;
this.price = price;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setPrice(int price) {
this.price = price;
}
public String toString() {
return "name: " + name + "age: " + age + "price: " + price;
}
}
스트림을 활용한 연산 수행
- 고객의 명단을 출력합니다.
- 여행의 총 비용을 계산합니다.
- 고객 중 20세 이상인 사람의 이름을 정렬하여 출력합니다.
customerList.stream().map(c->c.getName()).forEach(s->System.out.println(s));
여기에서 map(c->c.getName()) 가 중간연산이고 forEach(s->System.out.println(s)) 가 최종연산이다.
중간 연산은 여러 번 쓰일 수 있고, 중간연산은 최종연산이 수행될 때 한 번에 일괄적으로 수행된다.
map 없이 forEach 만 있으면 toString 메서드에 의해 요소 전체 정보가 출력된다.
그래서 map(c->c.getName()) 을 하면 이름만 출력된다.
sorted()를 사용할 때 어떻게 정렬할 건지를 정할 comparable이 구현이 되어 있어야 한다
public class TravelTest {
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<>(); // List 생성
customerList.add(customerLee);
customerList.add(customerKim);
customerList.add(customerHong);
System.out.println("== 고객 명단 추가된 순서대로 출력 =="); // 고객 명단 출력
customerList.stream().map(c->c.getName()).forEach(s->System.out.println(s));
int total = customerList.stream().mapToInt(c->c.getPrice()).sum(); // 총 여행 비용 출력
System.out.println("총 여행 비용은 :" + total + "입니다");
System.out.println("== 20세 이상 고객 명단 정렬하여 출력 =="); // 20세 이상 고객 명단 출력
customerList.stream().filter(c->c.getAge() >= 20).map(c->c.getName()).sorted().forEach(s->System.out.println(s));
}
}
'✅🌲강의 복습 노트 > 패캠 JavaSpring 강의,코드 복습' 카테고리의 다른 글
| Part2. 6-9 예외 처리하기와 미루기 (5) | 2025.08.14 |
|---|---|
| Part2. 6-8 예외 처리는 왜 해야 하나? 자바에서 제공되는 클래스들 (2) | 2025.08.08 |
| Part2. 6-6 연산 수행에 대한 구현을 할 수 있는 reduce()연산 (Stream의 메서드) (1) | 2025.07.29 |
| Part2. 6-5 스트림(Stream : 통합 연산 도구) (3) | 2025.07.26 |
| Part2. 6-4 객체지향 프로그래밍 vs. 람다식 구현 (2) | 2025.07.26 |
Comments