본문 바로가기

개인적으로 공부한 것을 정리해 놓은 블로그입니다 틀린 것이 있으면 댓글 부탁 드립니다!


JAVA

JAVA 스터디 22 - 컬렉션 프레임웍과 함수형 인터페이스

반응형
인터페이스 메서드 설명
Collection boolean removeIf(Predicate<E> filter) 조건에 맞는 요소를 삭제
List void replaceAll(UnaryOperator<E> operator) 모든 요소를 변환하여 대체
Iterable void forEach(Consumer<T> action) 모든 요소에 작업 action 수행
Map V compute(K key,BiFunction<K,V,V>f) 지정된 키의 값에 작업 f를 수행
V computeIfAbsent(K key , Function<K,V> f) 키가 없으면 , 작업 f 수행 후추가
V computeIfPresent(K key , BiFunction<K,V,V>) f 지정된 키가 있을 때, 작업 f 수행
V merge(K key , BiFunction<V,V,V> f) 모든 요소에 병합한 f를 수행
void forEach(BiConsumer<K,V> action) 모든 요소에 작업 action을 수행
void replaceAll(BiFuntion<K,V,V> f) 모든 요소에 치환작업 f 를 수행

 

예제 코드

 

public class LamdaWithCollectionExam {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for(int i = 0 ; i < 10 ; i ++){
            list.add(i);
        }
        //list의 모든 요소를 , 과 함께 출력한다.
        list.forEach(i-> System.out.print(i+","));

        System.out.println();

        //list에서 2 또는 3의 배수를 제거
        list.removeIf(i->i%2==0 || i%3==0);
        list.forEach(i-> System.out.print(i+","));

        System.out.println();

        //list의 모든 요소에 10을 곱한다.
        list.replaceAll(i->i*10);
        System.out.println(list);

        Map<String,String> map = new HashMap<>();
        map.put("1","1");
        map.put("2","2");
        map.put("3","3");
        map.put("4","4");

        map.forEach((k,v)-> System.out.println("{"+k+","+v+"}"));
    }
}
반응형