[Stream] 정렬(sort), 루핑(peek, forEach, 매칭(allMatch, anyMatch, noneMatch)

정렬

- 중간 단계에서 요소를 정렬해서 최종 처리 순서를 변경할 수 있음.

- 객체요소일 경우 클래스가 Comparable을 구현하지 않으면 ClassCastException 발생

 

Comparable 인터페이스를 구현한 Student 클래스

public class Student implements Comparable<Student>{
	String name;
	int score;
	public Student(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	
	@Override
	public int compareTo(Student o) {
		return Integer.compare(score,o.score);
	}
}

예제 : 숫자요소는 오름차순, Student 객체 요소는 점수를 기준으로 오름차순!

public class SortingExample {
	public static void main(String[] args) {
		//숫자 요소일 경우
		IntStream intStream = Arrays.stream(new int[] {5,3,2,1,4});
		intStream
			.sorted().forEach(n->System.out.print(n+","));//오름차순
		System.out.println();
		
		//객체요소일 경우
		List<Student> studentList = Arrays.asList(
			new Student("가나다",30),
			new Student("라마바",10),
			new Student("사아자",20)
		);
		studentList.stream() //점수를 기준으로 오름차순 정렬
			.sorted().forEach(n -> System.out.print(n.getScore()+","));
		System.out.println();
		
		studentList.stream() //점수를 기준으로 내림차순 정렬.
			.sorted(Comparator.reverseOrder())
			.forEach(n-> System.out.print(n.getName()+"/"+n.getScore()+","));
	}
}
//1,2,3,4,5,
//10,20,30,
//가나다/30,사아자/20,라마바/10,

 

루핑

- 요소 전체를 반복하는 것

- peek() 메소드는 중간처리 메소드, 중간처리 단계에서 요소를 루핑하면서 추가적인 작업을 하기 위해 사용. 마지막에 사용하면 실행 안됨.(최종X)

- forEach() 메소드는 최종 처리 메소드, 이후에 다른 최종메소드 호출 불가

예제 : peek 중간호출, peek로 출력 후 결과집합 호출, forEach로 최종 출력.

public class LoopingExample {
	public static void main(String[] args) {
		int[] intArr = {1,2,3,4,5};
		
		System.out.println("[peek()를 마지막에 호출한 경우]");
		Arrays.stream(intArr)
			.filter(a -> a%2 ==0)
			.peek(n ->System.out.println(n)); //동작하지 않음.
		System.out.println("--");
		
		System.out.println("[최종 처리 메소드를 마지막에 호출한 경우]");
		int total = Arrays.stream(intArr)
			.filter(a -> a%2==0 ) //2의 배수만
			.peek(n -> System.out.println(n)) //동작함
			.sum();
		System.out.println("총합 : "+total);
		
		System.out.println("[forEach()를 마지막에 호출한 경우]");
		Arrays.stream(intArr)
			.filter(a-> a%2==0 ) //2의 배수만
			.forEach(n -> System.out.println(n));
	}
}
[peek()를 마지막에 호출한 경우]
--
[최종 처리 메소드를 마지막에 호출한 경우]
2
4
총합 : 6
[forEach()를 마지막에 호출한 경우]
2
4

 

매칭

- 최종 처리 단계에서 요소들이 특정 조건에 만족하는지 조사할 수 있도록 세가지 매칭 메소드 제공

- allMatch() : 모든 요소들이 매개값으로 주어진 Predicate의 조건을 만족하는지 조사

- anyMatch() : 최소한 한 개의 요소가 매개값으로 주어진 Predicate의 조건을 만족하는지 조사

- noneMatch() : 모든 요소들이 매개값으로 주어진 Predicate의 조건을 만족하지 않는지 조사

public class MatchExample {
	public static void main(String[] args) {
		int[] intArr = {2,4,6};
		
		boolean result = Arrays.stream(intArr)
				.allMatch( a-> a%2==0);
		System.out.println("모두 2의 배수인가? "+result);
		
		result = Arrays.stream(intArr)
				.anyMatch( a-> a%3==0);
		System.out.println("하나라도 3의 배수가 있는가 ? "+result);
		
		result = Arrays.stream(intArr)
				.noneMatch(a->a%3==0);
		System.out.println("3의 배수가 없는가? "+ result);
		
	}
}
//모두 2의 배수인가? true
//하나라도 3의 배수가 있는가 ? true
//3의 배수가 없는가? false

 

댓글

Designed by JB FACTORY