[Java] 스트림
스트림(Stream)
📌 스트림(Stream)
: 데이터의 흐름.
📌 중간 연산(Intermediate Operation)
: 마지막이 아닌 위치에서 진행되어야 하는 연산.
📌 최종 연산(Terminal Operation)
: 마지막에 진행되어야 하는 연산.
📌 스트림 연산 : 지연(Lazy) 처리 방식으로 동작.
: 최종 연산을 진행하지 않으면, 중간 연산 결과는 스트림에 반영되지 않음.
최종 연산이 진행되어야, 중간 연산 결과가 스트림에 반영됨.
📌 스트림 생성에 필요한 데이터 인자로 전달 가능.
📌 두 개의 스트림을 하나의 스트림으로 생성 가능.
📄 StreamTest1.java
package stream;
import java.util.Arrays;
public class StreamTest1 {
public static void main(String[] args) {
int[] ar = { 1, 2, 3, 4, 5 };
int sum = Arrays.stream(ar)
.filter(n -> n%2 == 1)
.sum();
System.out.println(sum); // 9
}
}
스트림(Stream) 생성 방법 - 배열
📌 배열에 저장된 데이터를 대상으로 스트림 생성할 때 호출하는 대표 메소드.
public static <T> Stream<T> stream(T[] array)
📄 StreamTest2.java
package stream;
import java.util.Arrays;
import java.util.stream.Stream;
public class StreamTest2 {
public static void main(String[] args) {
String[] colors = { "red", "blue", "green", "yellow", "orange" };
Stream<String> st = Arrays.stream(colors);
st.forEach(s -> System.out.print(s + " ")); // red blue green yellow orange
// Arrays.stream(colors)
// .forEach(s -> System.out.print(s + " ")); // red blue green yellow orange
}
}
+ 추가 설명
- forEach : 인스턴스 메소드.
- forEach 매개변수형 : Consumer<T>
→ void accept(T t) 추상 메소드 구현한 람다식을 인자로 전달해야 함.
forEach가 void accept(T t) 메소드 호출함.
- forEach는 최종 연산.
→ 중간 연산 없이 최종 연산 진행 가능.
📌 기본 자료형의 값을 담고 있는 배열을 대상으로 스트림 생성할 때 호출하는 메소드.
public static IntStream stream(int[] array)
public static IntStream stream(int[] array, int startInclusive, int endExclusive)
📄 StreamTest3.java
package stream;
import java.util.Arrays;
public class StreamTest3 {
public static void main(String[] args) {
double[] d = { 2.3, 0.5, -3.9, 9.2, -7.1 };
Arrays.stream(d)
.forEach(i -> System.out.print(i + " ")); // 2.3 0.5 -3.9 9.2 -7.1
System.out.println();
Arrays.stream(d, 1, 3) // 1번 인덱스부터 3번 인덱스 전 까지.
.forEach(i -> System.out.print(i + " ")); // 0.5 -3.9
System.out.println();
}
}
스트림(Stream) 생성 방법 - 컬렉션 인스턴스
📌 컬렉션 인스턴스를 대상으로 스트림 생성하는 방법
default Stream<E> stream()
📄 StreamTest4.java
package stream;
import java.util.Arrays;
import java.util.List;
public class StreamTest4 {
public static void main(String[] args) {
List<String> li = Arrays.asList("apple", "blueberry", "banana", "cherry", "watermelon");
li.stream()
.forEach(s -> System.out.print(s + " ")); // apple blueberry banana cherry watermelon
System.out.println();
}
}
스트림(Stream) 생성 방법 - 필요한 데이터 직접 전달
📌 Stream<T> 인터페이스에 정의된 static 메소드
static <T> Stream<T> of(T t)
static <T> Stream<T> of(T...values)
📌 IntStream, DoubleStream, LongStream
: 불필요한 오토 박싱, 오토 언박싱 피할 수 있음.
static IntStream of(int t)
static IntStream of(int...values)
static DoubleStream of(double t)
static DoubleStream of(double...values)
static LongStream of(long t)
static LongStream of(long...values)
📌 범위 내에 있는 값들로 스트림 구성하도록 하는 메소드
range(startInclusive, endExclusive) | startInclusive부터 endExclusive 전까지 스트림. |
rangeClosed(startInclusive, endExclusive) | startInclusive부터 endExclusive 까지 스트림. |
static IntStream range(int startInclusive, int endExclusive)
static IntStream rangeClosed(int startInclusive, int endExclusive)
static LongStream range(Long startInclusive, Long endExclusive)
static LongStream rangeClosed(Long startInclusive, Long endExclusive)
📄 OfStreamTest.java
package stream2;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class OfStreamTest {
public static void main(String[] args) {
Stream.of(1, 2, 3, 4, 5)
.forEach(n -> System.out.print(n + " ")); // 1 2 3 4 5
System.out.println();
Stream.of("Hello Nice to meet you")
.forEach(s -> System.out.print(s + " ")); // Hello Nice to meet you
System.out.println();
List<String> li = Arrays.asList("apple", "banana", "cherry");
Stream.of(li)
.forEach(i -> System.out.print(i + " ")); // [apple, banana, cherry]
System.out.println();
}
}
스트림(Stream) 연결
📌 두 개의 스트림을 하나의 스트림으로 생성 가능.
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
static <T> Stream<T> concat(Stream<T> a, Stream<T> b)
📌 IntStream, DoubleStream, LongStream
static IntStream concat(IntStream a, IntStream b)
static DoubleStream concat(DoubleStream a, DoubleStream b)
static LongStream concat(LongStream a, LongStream b)
📄 ConcatStreamTest.java
package stream2;
import java.util.stream.Stream;
public class ConcatStreamTest {
public static void main(String[] args) {
Stream<String> s1 = Stream.of("apple", "banana");
Stream<String> s2 = Stream.of("cherry", "pear");
Stream.concat(s1, s2)
.forEach(s -> System.out.print(s + " ")); // apple banana cherry pear
}
}