대충 이렇게 사용..

그냥 단순히 얘기해 변수에 함수를 대입하는것.. 리턴과는 다르다.

public static void main(String[] args) {

List<Integer> list = Arrays.asList(3, 4, 5, 6, 7, 8);

list.stream().forEach(value -> {
System.out.println(value);
System.out.println(value - 1);

});

Func ad = (int a, int b) -> a + b;

int sum1 = sumAll(list, n -> true); // 전부다 합
int sum2 = sumAll(list, n -> n % 2 == 0); // 짝수 합
int sum3 = sumAll(list, n -> n > 5); // 5보다큰수 합

}
public static int sumAll(List<Integer> numbers, Predicate<Integer> p) {
int total = 0;
for (int number : numbers) {
if (p.test(number)) {
total += number;
}
}
return total;
}

@FunctionalInterface
interface Func {
public int Cal(int a, int b);
}


위에서 Predicate 라는 인터페이스는 1.8 부터 지원되는 java.util.function 에 있는

functionInterface 임..  test(object) 라는 함수를 가지고있음




밑의 자료는 퍼온것 스트림에 관해..




3.1. Get Stream

먼저 Stream API를 사용하려면 stream을 얻어와야 합니다. 얻는 방법은 다음과 같습니다.

Arrays.asList(1,2,3).stream(); // (1)
Arrays.asList(1,2,3).parallelStream(); // (2)

콜렉션 관련 객체라면 stream을 얻어올 수 있습니다. (1)번 방법은 일반적인 stream을 가져오는 것이고 (2)번 방법은 병렬로 stream을 가져옵니다.

3.2. Working Stream

실제로 얻어온 stream에 연산을 해봅시다. 주요하게 쓰이는 몇가지 API만 살펴봅시다.

3.2.1. forEach

stream의 요소를 순회해야 한다면 forEach를 활용할 수 있습니다.

Arrays.asList(1,2,3).stream()
					.forEach(System.out::println); // 1,2,3

3.2.2. map

stream의 개별 요소마다 연산을 할 수 있습니다. 아래의 코드는 리스트에 있는 요소의 제곱 연산을 합니다.

Arrays.asList(1,2,3).stream()
					.map(i -> i*i)
					.forEach(System.out::println); // 1,4,9

3.2.3. limit

stream의 최초 요소부터 선언한 인덱스까지의 요소를 추출해 새로운 stream을 만듭니다.

Arrays.asList(1,2,3).stream()
					.limit(1)
					.forEach(System.out::println); // 1

3.2.4. skip

stream의 최초 요소로부터 선언한 인덱스까지의 요소를 제외하고 새로운 stream을 만듭니다.

Arrays.asList(1,2,3).stream()
					.skip(1)
					.forEach(System.out::println); // 2,3

3.2.5. filter

stream의 요소마다 비교를 하고 비교문을 만족하는 요소로만 구성된 stream을 반환합니다.

Arrays.asList(1,2,3).stream()
					.filter(i-> 2>=i)
					.forEach(System.out::println); // 1,2

3.2.6. flatMap

stream의 내부에 있는 객체들을 연결한 stream을 반환합니다.

Arrays.asList(Arrays.asList(1,2),Arrays.asList(3,4,5),Arrays.asList(6,7,8,9)).stream()
					.flatMap(i -> i.stream())
					.forEach(System.out::println); // 1,2,3,4,5,6,7,8,9

3.2.7. reduce

stream을 단일 요소로 반환합니다.

Arrays.asList(1,2,3).stream()
					.reduce((a,b)-> a-b)
					.get(); // -4

이 코드는 조금 설명이 필요할 것 같습니다. 우선, 첫번째 연산으로 1과 2가 선택되고 계산식은 앞의 값에서 뒤의 값을 빼는 것이기 때문에 결과는 -1이 됩니다. 그리고 이상태에서 -1과 3이 선택되고 계산식에 의해 -1-3이 되기 때문에 결과로 -4가 나옵니다. 뒤로 추가 요소가 있다면 차근차근 앞에서부터 차례대로 계산식에 맞춰 계산하면 됩니다.

3.2.8. collection

아래의 코드들은 각각의 메소드로 콜렉션 객체를 만들어서 반환합니다.

Arrays.asList(1,2,3).stream()
					.collect(Collectors.toList());
Arrays.asList(1,2,3).stream()
					.iterator();