import java.util.function.BiFunction;
public class BifunctionTest {
public static void main(String... strings) {
// BiFunction<T, U, R> : 두 입력 → 하나의 출력
BiFunction<Integer, Integer, String> sumToString = (a, b) -> "합: " + (a + b);
System.out.println(sumToString.apply(3, 4)); // 합: 7
BiFunction<Integer, Integer, Integer> adder = (a, b) -> a + b;
System.out.println(adder.apply(3, 5)); // 8
BiFunction<String, Integer, String> repeater = (s, n) -> s.repeat(n);
System.out.println(repeater.apply("hi", 3)); // hihihi
}
}
import java.util.HashMap;
import java.util.Map;
public class BiFunctionMapTest {
public static void main(String... strings) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Bob", 90);
scores.put("Alice", 80);
// compute
scores.compute("Alice", (key, value) -> value + 5); // key = Alice, oldValue = 80
scores.compute("Charlie", (key, value) -> (value == null) ? 70 : value + 10); // key = Charlie, oldValue = null, NullPointerException 방지 필요
System.out.println(scores); // {Bob=90, Alice=85, Charlie=70}
// computeIfPresent
scores.computeIfPresent("Charlie", (key, value) -> value * 2);
scores.computeIfPresent("Alpha", (key, value) -> value * 0); // 키가 없으면 아무 작업 안함.
System.out.println(scores); // {Bob=90, Alice=85, Charlie=140}
// merge
scores.merge("Alice", 10, (oldVal, newVal) -> oldVal + newVal); // 기존값 85 + 10
scores.merge("David", 15, (oldVal, newVal) -> oldVal + newVal); // 키가 없으니, 15
System.out.println(scores); // {Bob=90, Alice=95, Charlie=140, David=15}
}
}
import java.util.HashMap;
import java.util.Map;
public class FunctionMapTest {
public static void main(String... strings) {
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
// computeIfAbsent
map.computeIfAbsent("b", k -> k.length() * 10); // map = {a=1, b=10}
map.computeIfAbsent("a", k -> 100); // map = {a=1, b=10} -> 값 변경 없음, 이미 값 있는 키는 무시
System.out.println(map);
// getOrDefault
int val = map.getOrDefault("c", 0); // c가 없으면 0 반환
System.out.println(val); // 0
// replaceAll
map.replaceAll((k, v) -> v * 2); // BiFunction
System.out.println(map); // {a=2, b=20}
}
}