코딩 기록들
자바의 다양한 기능들 5. 패키지 여행비용 계산하기 예제(스트림 활용) 본문
여행사에 패키지 여행상품이 있다.
- 여행비용 : 20세이상 100만원, 미만은 50만원
- 고객 3명이 패키지여행을 떠난다고했을때, 비용계산과 고객명단 검색등에 대한 연산을 스트림을 활용해 구현
- 고객에 대한 클래스 만들고 ArrayList로 고객 관리
- custer class 만들고 ArrayList로 관리
힌트
1. 고객의 명단을 출력
2. 여행의 총비용 계산
3. 고객중 20세이상인 사람의 이름을 '정렬'(sorted())하여 출력
고객정보
Customer | CustomerLee | CustomerKim | CustomerHong |
이름 | 이유신 | 김유신 | 홍유신 |
나이 | 40 | 20 | 13 |
비용 | 100 | 100 | 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;
}
}
import java.util.ArrayList;
import java.util.List;
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);
// ArrayList 만들기
List<TravelCustomer> customerList = new ArrayList<>();
customerList.add(customerLee);
customerList.add(customerKim);
customerList.add(customerHong);
System.out.println("== 고객정보 전부 호출 ==");
customerList.stream().forEach(s->System.out.println(s));
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세 이상 고객 이름 정렬하여 출력 ==");
customerList.stream().filter(c->c.getAge() >= 20).map(c->c.getName()).sorted().forEach(s->System.out.println(s));
}
}
중간연산은 여러개 쓰일 수 있음! (단, 최종연산은 1번만) -> 최종연산이 불릴때 중간연산도 처리됨
- map(c->c.getName()) -> 중간연산
- forEach() -> 최종연산
출력
'Java' 카테고리의 다른 글
[자바의 다양한 기능들] 7.1 자바의 입출력을 위한 I/O stream (1) | 2024.01.11 |
---|---|
[자바의 다양한 기능들] 6-2. 예외처리하기와 미루기(2) (1) | 2024.01.09 |
자바의 다양한 기능들 4. reduce() (1) | 2024.01.09 |
자바의 다양한 기능들 3.스트림 Stream (1) | 2024.01.07 |
자바의 다양한 기능들 2. 함수형 프로그래밍과 람다식 Lamada expression (0) | 2024.01.04 |