람다식
익명 함수 객체 !
-> 객체의 선언과 생성 동시에 !
interface Calculator {
int operate(int x, int y);
}
Calculator calc = (x,y) -> x + y;
Calculator calc = new Calculator() {
public int operate(int x, int y) {
return x + y;
}
}
↪ Calculator 인터페이스를 구현한 익명 객체를 람다식으로 대체 한 것!!
함수형 인터페이스
단 하나의 추상 메서드만 선언된 인터페이스
=> 람다식은 함수형 인터페이스가 있어야 사용 가능!
interface Calculator {
int operate(int a,int b); //public abstract int operate(int a, int b);
}
Calculator add = (a,b) -> a + b;
Calculator multiply = (a,b) -> a*b;
add.operate(4,5); //9
multiply.operate(4,6); //20
public static void RunOperation(Calculator calc, int x, int y) {
System.out.println(calc.operate(x,y));
}
RunOperation(add,4,5);
RunOperation((a,b) -> a + b, 4, 5); //위와 같음
컬렉션 프레임웍과 함수평 인터페이스
import java.util.function.*;
import java.util.*;
class LamdaEx5 {
public static void main(String[] args) {
Supplier<Integer> s = () -> (int)(Math.random() * 100) + 1;
Consumer<Integer> c = i -> System.out.print(i + ", ");
Predicate<Integer> p = i -> i % 2 == 0;
Function<Integer, Integer> f = i -> i % 10 * 10;
List<Integer> list = new ArrayList<>();
makeRandomList(s, list);
System.out.println(list);
printEvenNum(p, c, list);
List<Integer> newList = doSomething(f, list);
System.out.println(newList);
}
public static <T> List<T> doSomething(Function<T,T> f, List<T> list) {
List<T> newList = new ArrayList<>();
for(T i : list) {
newList.add(f.apply(i)); //list의 요소의 1의자리요소만 *10 해서 저장
}
return newList;
}
public static <T> void printEvenNum(Predicate<T> p, Consumer<T> c, List<T> list) {
System.out.print("[");
for(T i : list) {
if(p.test(i)) { // i % 2 == 0인 요소만
c.accept(i); //조건에 해당되는 요소 System.print.print( i + ", ")
}
}
System.out.println("]");
}
public static <T> void makeRandomList(Supplier<T> s, List<T> list) {
for(int i = 0; i < 10; i++) {
list.add(s.get()); //랜덤 숫자 저장
}
}
}
[92, 16, 93, 1, 63, 17, 88, 16, 84, 27]
[92, 16, 88, 16, 84, ]
[20, 60, 30, 10, 30, 70, 80, 60, 40, 70]
스트림
스트림이란 ?
데이터를 추상화하여 표준화 된 방법으로 다루는 것
- 스트림생성
- 중간연산
- 최종연산
중간연산
- 자르기
skip(), limit()
- 걸러내기
filter(), distinct()
- 정렬하기
sorted()
Comparator.정렬기준
- 변환하기
map() & flatMap()
- 조회하기
peek()
최종연산
reduce() : 전체 리듀싱
collect() : 그룹별 리듀싱
- partictiongBy() : 2분할
- groupBy() : 그룹별
forEach()
findFirst()
findAny()
allMatch(), anyMatch, noneMatch()