Java 스트림

LIM JAEHO·2022년 7월 3일
0

Java 학습

목록 보기
19/19

Stream 스트림

배열, 컬렉션 등의 데이터를 하나씩 참조해 처리가능한 기능이다.
스트림을 사용하면 for문을 줄여 코드를 간결하게 만들어줄 수 있다.

스트림의 3단계

  • Stream 생성
  • 중개연산
  • 최종연산

Stream 생성

// 배열 스트림
System.out.println("=== 배열 스트림 ===");
String[] arr = new String[]{"a", "b", "c"};     // 외우기
String[] arr1 = {"a", "b", "c"};

Stream arrStream = Arrays.stream(arr);
Stream arrStream1 = Arrays.stream(arr1);

arrStream.forEach(System.out::println);
// arrStream.forEach(System.out::println);      => 최종연산을 만나면 스트림 연산을 또 사용하지 못한다.
arrStream1.forEach(System.out::println);
// arrStream1.forEach(System.out::println);     => 최종연산을 만나면 스트림 연산을 또 사용하지 못한다.

// 컬렉션 스트림
System.out.println("=== 컬렉션 스트림 ===");
ArrayList list = new ArrayList(Arrays.asList(1, 2, 3));     // 외우기

Stream colStream = list.stream();
colStream.forEach(System.out::println);
Stream colStream1 = list.stream();
colStream1.forEach(num -> System.out.println(num));

Stream streamBuilder = Stream.builder().add(1).add(2).add(3).build();
streamBuilder.forEach(System.out::println);
Stream streamGenerate = Stream.generate(() -> "abc").limit(3);
streamGenerate.forEach(System.out::println);
Stream streamIterate = Stream.iterate(10, n -> n * 2).limit(3);
streamIterate.forEach(System.out::println);
IntStream intStream = IntStream.range(1, 5);
intStream.forEach(System.out::println);

중개 연산

// filter
IntStream intStream1 = IntStream.range(1, 10).filter(n -> n % 2 == 0);
intStream1.forEach(System.out::println);

// map
IntStream intStream2 = IntStream.range(1, 10).map(n -> n + 1);
intStream2.forEach(n -> System.out.print(n + " "));
System.out.println();

// sorted
IntStream intStream3 = IntStream.builder().add(5).add(1).add(3).build();
IntStream intStream4 = intStream3.sorted();
intStream4.forEach(System.out::println);

최종 연산

// sum
int sum = IntStream.range(1, 5).sum();

// average
double average = IntStream.range(1, 5).average().getAsDouble();

// min
int min = IntStream.range(1, 5).min().getAsInt();

// max
int max = IntStream.range(1, 5).max().getAsInt();

System.out.println(sum);
System.out.println(average);
System.out.println(min);
System.out.println(max);

// reduce
Stream<Integer> streamInt = new ArrayList<>(Arrays.asList(1, 2, 3)).stream();
System.out.println(streamInt.reduce((x, y) -> x + y).get());

// forEach
IntStream.range(1, 10).filter(n -> n==5).forEach(System.out::println);

0개의 댓글