Comparator인터페이스를 이용해서 정렬방식을 재정의 할 수 있다.
Stream<클래스> sorted(Comparator<? super Student> comparator)
- 추상 메소드
compare: 매개변수로 해당 클래스 두개를 받음'
public int compare(클래스명 o1, 클래스명 o2){return Integer.compare(o1.get메소드,o2.get메소드)
}`
- 익명의 내부클래스(클래스 Student)
ArrayList<Student> as = new ArrayList<Student>(); Stream<Student> s = as.stream(); // // // Comparator<Student> com = new Comparator<Student>(){ @Override public int compare(Student o1, Student o2){ return Integer.compare(o1.getScore(),o2.getScore()); // 오름차순 정렬 } }; //출력 s.sorted().forEach(t->System.out.println(t));
- 람다식
as.stream() .sorted((Student o1, Student o2)-> {return Integer.compare(o1.getScore(),o2.getScore());}) .forEach(t->System.out.println(t);
- 자료형 생략가능, return문은 return,중괄호,세미콜론 생략가능
as.stream().sorted((o1,o2)->Integer.compare(o1.getScore(),o2.getScore())), .forEach(t->System.out.println(t);