Java & Kotlin

[Java 기능] 스트림 활용

Sue 2022. 2. 15. 14:10

문제

여행사에 패키지 여행 상품이 있습니다. 여행 비용은 15세 이상은 100만원, 그 미만은 50만원 입니다. 고객 세 명이 패키지 여행을 떠난다고 했을 때 비용 계산과 고객 명단 검색등에 대한 연산을 스트림을 활용하여 구현해 봅니다. 고객에 대한 클래스를 만들고 ArrayList로 고객을 관리 합니다.

고객 정보는 다음과 같습니다.

CustomerLee
이름 : 이순신
나이 : 40
비용 : 100

CustomerKim
이름 : 김유신
나이 : 20
비용 : 100

CustomerHong
이름 : 홍길동
나이 :13
비용 : 50

 

Customer.java
package ch07;

public class Customer {
	
	private String name;
	private int age;
	private int expense;
	
	Customer(String name, int age, int expense) {
		this.name = name;
		this.age = age;
		this.expense = expense;
	}

	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 getExpense() {
		return expense;
	}

	public void setExpense(int expense) {
		this.expense = expense;
	}
    
    	@Override
	public String toString() {
		return "이름:" + name + " 나이:" + age + " 비용:" + expense;
	}
	
}

 

CustomerTest.java

람다식 변수 연산에 따라 다르게 써주자..!

package ch07;

import java.util.ArrayList;

public class CustomerTest {
	
	public static void main(String[] args) {
		
		Customer customerLee = new Customer("이순신", 40, 100);
		Customer customerKim = new Customer("김유신", 20, 100);
		Customer customerHong = new Customer("홍길동", 13, 50);
		
		ArrayList<Customer> arr = new ArrayList<>();
		arr.add(customerHong);
		arr.add(customerKim);
		arr.add(customerLee);
		
		System.out.println("**고객 정보 출력**");
		arr.stream().forEach(s->System.out.println(s));
		System.out.println();
		
		System.out.println("**고객 명단 출력**");
		arr.stream().map(s->s.getName()).forEach(s->System.out.println(s));
		System.out.println();
		
		System.out.println("**비용 합계 출력**");
		int total = arr.stream().mapToInt(s->s.getExpense()).sum();
		System.out.println(total);
		System.out.println();
		
		System.out.println("**20세 이상의 고객 이름 정렬하여 출력**");
		arr.stream().filter(s->s.getAge() >= 20).map(s->s.getName()).sorted().forEach(n->System.out.println(n));
	}

}

 

수행 결과
**고객 정보 출력**
이름:홍길동 나이:13 비용:50
이름:김유신 나이:20 비용:100
이름:이순신 나이:40 비용:100

**고객 명단 출력**
홍길동
김유신
이순신

**비용 합계 출력**
250

**20세 이상의 고객 이름 정렬하여 출력**
김유신
이순신