김찬진의 개발 블로그
[23/07/20] 기타 함수형 인터페이스 본문
기본 함수형 인터페이스
Supplier<T>: T get()
Consumer<T> : void accept(T t, U u)
Function<T, R> : R apply(T t)
Predicate<T> : boolean test(T t, U u)
매개변수가 2개인 함수형 인터페이스
BiConsumer<T, U> : void accept(T t, U u)
BiFunction<T, U, R> : R apply(T t, U u)
BiPredicate<T, U> : boolean test(T t, U u)
매개변수와 반환값의 타입이 일치하는 함수형 인터페이스
UnaryOperator<T> : T apply(T t)
BinaryOperator<T>: T apply(T t, T t)
컬렉션 프레임워크와 관련된 함수형 인터페이스
Collection :
boolean removeIf(Predicate<E> filter)
List :
void replaceAll(UnaryOperator<E> operator)
Iterable :
void forEach(Consumer<T> action)
Map:
V compute(K key, BiFunction<K, V, V> f)
V computeIfAbsent(K key, Function<K, V> f)
V computeIfPresent(K key, BiFunction<K, V, V> f)
V merge(K key, V value, BiFunction<V, V, V> f)
void forEach(Biconsumer<K, V> action)
void replaceAll(BiFunction<K, V, V> f)
package functionalInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
public class LambdaEx4 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
for(int i=0; i<10; i++) {
list.add(i);
list2.add(i);
}
System.out.println("------------- forEach ------------- ");
// list 모든 요소 출력
// 생략 후
list.forEach(i -> System.out.print(i + ", "));
System.out.println();
// 생략 전
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer i) {
System.out.print(i + ", ");
}
});
System.out.println();
System.out.println("------------- removeIf ------------- ");
// list 2의 배수, 3의 배수 제거 후 list 출력
// 생략 후
list.removeIf(x -> x%2==0 || x%3==0);
System.out.println(list);
// 생략 전
list2.removeIf(new Predicate<Integer>() { // line38
@Override
public boolean test(Integer i) {
return i%2==0 || i%3==0;
}
});
System.out.println(list2);
System.out.println("------------- replaceAll ------------- ");
// list 모든 요소에 10 곱하고 list 출력
// 생략 후
list.replaceAll(i -> i*10);
System.out.println(list);
// 생략 전
list2.replaceAll(new UnaryOperator<Integer>() {
@Override
public Integer apply(Integer i) {
return i*10;
}
});
System.out.println(list2);
System.out.println("------------- forEach ------------- ");
Map<String, String> map = new HashMap<>();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
// 생략 후
map.forEach((k,v) -> System.out.print("{" + k + ", " + v + "}, "));
System.out.println();
// 생략 전
map.forEach(new BiConsumer<String, String>() {
@Override
public void accept(String k, String v) {
System.out.print("{" + k + ", " + v + "}, ");
}
});
}
}
'1일1배움 > Java' 카테고리의 다른 글
[23/07/23] Arrays와 Array의 차이 (0) | 2023.07.23 |
---|---|
[23/07/20] 쓰레드 (0) | 2023.07.20 |
[23/07/20] Optional (0) | 2023.07.20 |
[23/07/20] 메서드 참조 :: (0) | 2023.07.20 |
[23/07/18] Comparable, Comparator (0) | 2023.07.18 |
Comments