문제
1- 고객 명단 출력
2- 여행의 총 비용 계산
3- 고객 중 20세 이상인 사람의 이름을 정렬하여 출력
Step1. Customer 클래스 만들고
Step2. ArrayList<Customer>로 관리
package Basic_Grammar.chap6.ch03StreamQuiz;
import java.util.ArrayList;
import java.util.List;
public class CustomerTest {
public static void main(String[] args) {
List<Customer> customers=new ArrayList<>();
Customer lee=new Customer();
lee.setCustomerName("이순신");
lee.setAge(40);
lee.setCost(100);
Customer kim=new Customer();
kim.setCustomerName("김유신");
kim.setAge(20);
kim.setCost(50);
Customer hong=new Customer();
hong.setCustomerName("홍길동");
hong.setAge(13);
hong.setCost(50);
customers.add(lee);
customers.add(kim);
customers.add(hong);
System.out.println("전체 고객 명단 출력");
customers.stream().forEach(customer ->
System.out.println(customer.getCustomerName())
);
System.out.println("회원들 여행의 총 비용");
System.out.println(customers.stream().mapToInt(c->c.getCost()).sum());
System.out.println("20세 이상 고객 명단 출력");
customers.stream().filter(customer -> customer.getAge()>=20).forEach(customer -> System.out.println(customer.getCustomerName()+"의 나이:"+customer.getAge()));
System.out.println("20세 이상 고객 명단 출력(가나다 순으로 정렬)");
customers.stream().filter(customer -> customer.getAge()>=20).map(c->c.getCustomerName()).sorted().forEach(name -> System.out.println(name));
}
}
실행결과
'JAVA > Java2021-3' 카테고리의 다른 글
예외처리 handling2 (try ~catch~finally 문, try-with-resources) (0) | 2021.10.13 |
---|---|
예외처리 handling1 (try ~catch 문) (0) | 2021.10.13 |
오류(error),예외(Exception) (0) | 2021.10.13 |
Stream 에 대해 연산을 직접 구현하는 reduce()메서드 (0) | 2021.10.12 |
스트림(Stream) 과 스트림 메서드(중간연산, 최종연산) (0) | 2021.10.11 |