-
Lambda 식 / ArrayList를 사용한 Stream 연산JAVA 2020. 5. 28. 20:09728x90
고객 Class
public class Customer { private String name; private int age; private int price; public Customer(String name, int age, int price) { super(); this.name = name; this.age = age; 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 class CustomerTest { public static void main(String[] args) { // 고객 리스트 생성 ArrayList<Customer> list = new ArrayList<Customer>(); list.add(new Customer("김철수", 25, 250000)); list.add(new Customer("김영희", 50, 250000)); list.add(new Customer("박희수", 33, 250000)); list.add(new Customer("홍기영", 7, 100000)); // 고객 명단(이름) 출력 list.stream().map(c -> c.getName()).forEach(name -> System.out.println(name)); // 총 여행 비용 출력 int total = list.stream().mapToInt(c -> c.getPrice()).sum(); System.out.println("총 여행 비용은 " + total + "입니다"); // 20세 이상 고객 명단(이름) 출력 list.stream().filter(c -> c.getAge() >= 20).forEach(c -> System.out.println(c.getName())); } }
< 결과 >
728x90728x90'JAVA' 카테고리의 다른 글
Runnable 에서 변수 사용하기(final 를 변수처럼 사용하기) (0) 2020.11.10 ArrayList 객체 비교하기 (0) 2020.07.20 Comparable<T>, Comparator<T> 인터페이스 - 정렬방식 지정 (0) 2020.05.26 GenericType / 2019-12-12 (0) 2020.01.15