ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Lambda 식 / ArrayList를 사용한 Stream 연산
    JAVA 2020. 5. 28. 20:09
    728x90
    728x90

    고객 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()));
    		
    		
    		
    	}
    
    }
    

     

     

    < 결과 >

    728x90
    728x90
Designed by Tistory.