JAVA

스트림 중간 처리,최종 처리

연93 2022. 10. 29. 13:27
public class Student {
	private String name;
	private int score;
	
	public Student(String name, int score) {
		this.name = name;
		this.score = score;
	}
	
	//Getter메소드
	public String getName() {
		return name;
	}
	public int getScore() {
		return score;
	}
}
import java.util.Arrays;
import java.util.List;

public class MapAndReduceExample {

	public static void main(String[] args) {
		List<Student> studentList = Arrays.asList(
				new Student("홍길동", 10),
				new Student("김동연", 30),
				new Student("송지은", 30)
		);
		
		int sum = 0;
		for(int i=0; i < studentList.size(); i++) {
			Student stu = studentList.get(i);
			 
			sum += stu.getScore(); //총점
		}
		
		System.out.println(sum / studentList.size()); // 평균
		
		//스트림 이용
		double avg = studentList.stream()
				//중간처리(학생 객체를 점수로 매핑). 점수데이타를 모아둠.
				.mapToInt(stu -> stu.getScore())
				//최종처리(평균점수)
				.average()
				.getAsDouble();
		
		System.out.println("평균점수: " + avg);
		

	}

}

'JAVA' 카테고리의 다른 글

스트림  (0) 2022.10.29
중첩클래스와 중첩 인터페이스  (0) 2022.10.15
람다식  (0) 2022.10.12
제네릭 타입의 상속과 구현  (0) 2022.10.12
제네릭 와일드카드 타입  (0) 2022.10.12