JAVA/스트림
예제) 컬렉션과 스트림의 데이터 처리 비교
coding1842
2023. 8. 31. 13:51
예제
package ch12.sec01;
import java.util.*;
public class StreamDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < 10; i++)
list.add(r.nextInt(30));//10개의 임의의 데이터가 저장
List<Integer> gt10 = new ArrayList<>();
for(int i : list)//Random으로 만들어진 정수중에서 10보다 큰 수를 저장
if (i>10)
gt10.add(i);
Collections.sort(gt10);
System.out.println(gt10);
//리스트에 저장된 데이터가 순차적으로 흘러가면서
//filter를 거친다. 10보다 끝 수만 정렬
//정렬된 수를 하나씩 출력해라
list.stream()
.filter(i -> i > 10)
.sorted()
.forEach(x -> System.out.print(x + " "));
}
}
결과
[16, 19, 21, 26, 26]
16 19 21 26 26