본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

JAVA

java.util.function패키지: removeIf(Predicate<E> filter) replaceAll(UnaryOperator<E> operator) forEach(Consumer<? super T> action) compute(K key, BiFunction<K, V, V> f)

프레임워크를 더 유연하고 사용하기 쉽게, 새로운 기능을 적용할 수 있도록 하기위해 컬렉션 프레임워크에 다수의 디폴트 메서드가 추가되었다.
아래는 함수형 인터페이스를 사용하는 디폴트 메서드이다.

 

Collection
removeIf(Predicate<E> filter)
지정된 조건을 만족하는 요소를 컬렉션에서 제거

import java.util.ArrayList;
import java.util.Collection;

public class Main {
public static void main(String[] args) {
Collection<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

// 짝수를 제거하는 예시
numbers.removeIf(n -> n % 2 == 0);

System.out.println("After removing even numbers: " + numbers);
}
}

[출력결과]
After removing even numbers: [1, 3]

 

 

 

 

List
replaceAll(UnaryOperator<E> operator)
리스트의 각 요소에 대해 지정된 연산을 수행하고 결과로 대체

import java.util.ArrayList;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

// 각 요소를 제곱하는 예시
numbers.replaceAll(n -> n * n);

System.out.println("After squaring each element: " + numbers);
}
}

[출력결과]
After squaring each element: [1, 4, 9]

 

 

 

Iterable
forEach(Consumer<? super T> action)
각 요소에 대해 지정된 작업을 수행

import java.util.ArrayList;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

// 각 요소를 출력하는 예시
names.forEach(name -> System.out.println("Hello, " + name));
}
}
[출력결과]
Hello, Alice
Hello, Bob
Hello, Charlie

 

 

 

Map
compute(K key, BiFunction<K, V, V> f)
지정된 키에 대해 새 값을 계산하고 저장

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class Main {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 80);
scores.put("Bob", 90);

// "Alice"의 점수를 10점 증가시키는 예시
scores.compute("Alice", (name, score) -> score + 10);

System.out.println("Updated scores: " + scores);
}
}

[출력결과]
Updated scores: {Alice=90, Bob=90}