Java/객체지향

[객체지향][스트림/Stream] - 스트림의 중간연산(1)

얄루몬 2022. 3. 18. 11:14

https://youtu.be/G2lPQB42GL8?list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp 

📖본 포스팅은 '자바의 정석 - 남궁성 저자' 님의 책과 유튜브 강의를 보고 작성되었습니다.


[스트림의 중간연산]

  • 스트림 자르기 - skip(), limit()
    • skip(long n) - n개 숫자만큼 건너 뛰기
    • limit(long maxSize) - maxSize 이후의 요소는 잘라냄
  • 스트림의 요소 걸러내기 - filter(), distinct()
    • filter() - 조건에 맞지 않는 요소 제거
    • distinct()  - 중복 제거
  • 스트림 정렬하기 - sorted()
    • sorted() - 스트림 요소의 정렬(기본 정렬, 지정 정렬)

  • Comparator의 comparing()으로 정렬 기준 제공

[실습]

package javajungsuk;

import java.util.Comparator;
import java.util.stream.Stream;

public class Java14_10 {

	public static void main(String[] args) {
		Stream<Student> studentStream = Stream.of(
				new Student("이자바", 3, 300),
				new Student("김자바", 1, 200),
				new Student("안자바", 2, 100),
				new Student("박자바", 2, 150),
				new Student("소자바", 3, 290),
				new Student("나자바", 3, 180)
				);
		studentStream.sorted(Comparator.comparing(Student::getBan)//1. 반별 정리
			.thenComparing(Comparator.naturalOrder()))//2. 기본 정렬
			.forEach(System.out::println);
		
	}

}
class Student implements Comparable<Student>{
	String name;
	int ban;
	int totalScore;
	
	public Student(String name, int ban, int totalScore) {
		super();
		this.name = name;
		this.ban = ban;
		this.totalScore = totalScore;
	}

	@Override
	public String toString() {
		return String.format("[%s, %d, %d]", name, ban, totalScore);
	}

	public String getName() {
		return name;
	}

	public int getBan() {
		return ban;
	}

	public int getTotalScore() {
		return totalScore;
	}
	public int compareTo(Student s) {
		return s.totalScore - this.totalScore;
	}

}