728x90

스트림이란?

자바의 스트림 또한 자바8부터 지원하는 문법으로 컬렉션 데이터를 for문 없이 함수형 프로그래밍을 할 수 있으며

병렬처리가 가능하단 장점이 있습니다.

 

사용법으로는 

arrayList.stream().filter().map().sorted() 이런식으로 사용할 수 있습니다.

 

위에서 보면 filter, map, sorted등 stream api에서 제공하는 여러 함수들이 있는데 함수들의 기능들을 알면 

필터링, 맵핑, 소팅, 출력등을 쉽게 제어할 수 있습니다.

아래 링크에 들어가면 함수별 기능이 있고, 필요에따라 사용하실 수 있습니다.

 

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html 

 

Stream (Java Platform SE 8 )

A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream: int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight())

docs.oracle.com

 

간단한 예제를 하나 보고 넘어가면 아래와 같이 String으로 구성된 ArrayList를 순서대로 출력을 할 수도 있고,

sorted()함수를 이용해 정렬 후 출력을 할 수 있습니다.

public class ArrayListStreamTest {
    public static void main(String[] args) {
        List<String> sList = new ArrayList<String>();
        sList.add("ddd");
        sList.add("bbb");
        sList.add("ccc");

        Stream<String> stream = sList.stream();
        stream.forEach(s-> System.out.println(s + " "));
        System.out.println();

        sList.stream().sorted().forEach(s-> System.out.println(s));
    }
}

또한 아래 예제처럼 int로 구성된 리스트중에서 filter()함수를 사용하여 리스트의 숫자중 3보다 큰수의 합만 구할 수도 있습니다.

public class intArraySum {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6};

        int result = Arrays.stream(arr).filter(c -> c > 3).sum();
        System.out.println(result);
    }
}

 

+ Recent posts