상세 컨텐츠

본문 제목

[Collection, Map, Lambda] replaceAll : 함수형 인터페이스를 파라미터로 가지는 컬렉션 메소드

Java

by kwanghyup 2020. 6. 19. 22:08

본문

import java.util.*;
import java.util.function.BiFunction;

public class replaceAllTest {
    /*
        replaceAll( BiFunction<T, U, R> )
            R apply(T t, U u) 구현
            T : 현재 map의 key
            U : 현재 map의 value
            V : 메소드 수행 후 map의 value
    */
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("lee",22);
        map.put("lim",32);
        map.put("kim",34);
        map.put("park",44);

        map.replaceAll(new BiFunction<String, Integer, Integer>() {
            @Override
            public Integer apply(String key, Integer value) {
                if(key.startsWith("l")) { // "l"로 시작하는 key에 대하여
                    value = value * 10;
                    return value;
                }
                return value;
            }
        });

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

 

람다

import java.util.*;

public class replaceAllTest {

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("lee",22);
        map.put("lim",32);
        map.put("kim",34);
        map.put("park",44);

        map.replaceAll((key, value) -> {
            if(key.startsWith("l")) {
                value = value * 10;
                return value;
            }
            return value;
        });

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

관련글 더보기

댓글 영역