Notice
Recent Posts
Recent Comments
250x250
Creative Code
람다 함수,stream 본문
728x90
람다함수 기본 사용법
@FunctionalInterface //람다함수로 사용할 인터페이스에 써준다
interface Calculator { //람다를 쓸때에는 매서드를 2개이상 입력할수 없다)
int sum(int a, int b , int c);
}
public class Main {
public static void main(String[] args) {
Calculator mc = (a,b,c) -> a+b+c; // 람다적용
int result = mc.sum(3,4,5);
System.out.println(result);
}
}
**BiFunction(람다함수의 인수가 2개일때)
import java.util.function.BiFunction; // 람다함수의 인수가 2개일때사용
public class Main {
public static void main(String[] args) {
BiFunction<Integer,Integer,Integer>mc = (a,b) -> a+b; //앞의 integer 2개는 입력자료형 , 뒤에 1개는 출력자료형이다.
int result = mc.apply(3,4); //BiFunction은 apply를 쓴다.
System.out.println(result);
}
}
**BinaryOperator
import java.util.function.BinaryOperator;
public class Main {
public static void main(String[] args) {
BinaryOperator<Integer>mc = (a,b) -> a+b; // 입력자료형과 출력자료형이 모두 동일하면 BinaryOperator 을 쓴다.
int result = mc.apply(3,4);
System.out.println(result);
}
}
**stream
import java.util.Arrays;
import java.util.Comparator;
public class Sample {
public static void main(String[] args) {
int[] data = {5, 6, 4, 2, 3, 1, 1, 2, 2, 4, 8};
int[] result = Arrays.stream(data) // IntStream을 생성한다.
.boxed() // IntStream을 Stream<Integer>로 변경한다.
.filter((a) -> a % 2 == 0) // 짝수만 걸러낸다.
.distinct() // 중복을 제거한다.
.sorted(Comparator.reverseOrder()) // 역순으로 정렬한다.
.mapToInt(Integer::intValue) // Stream<Integer>를 IntStream으로 변경한다.
.toArray() // int[] 배열로 반환한다.
;
}
}
728x90