상세 컨텐츠

본문 제목

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

Java

by kwanghyup 2020. 6. 19. 20:01

본문

예제01 

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

public class ComputeIfAbsentTest1 {
    /*
       computeIfAbsent( 맵의 키, Function<T, R> )
       구현 메소드 : R apply(T t);
       리턴값 R : map의 value
       파라미터 T : map의 key
    */
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("java","java study");
        map.put("jsp","JSP");
        map.put("spring","스프링");
        map.put("oracle","오라클");

        map.computeIfAbsent("python", new Function<String, String>() {
            @Override
            public String apply(String key) { // 파라미터는 맵의 키이 된다.
                System.out.println("파라미터 확인: "+ key);
                return "파이썬"; // 리턴값은 맵의 value이다.
            }
        });

        // 람다
        // mysql로 지정된 키가 없는 경우에 value값을 MYSQL로 지정한뒤 map에 추가
        map.computeIfAbsent("mysql",v-> v.toUpperCase());

        // 키값이 존재하는 경우 동작되지 않는다.
        map.computeIfAbsent("spring", key -> "스프링 부트");

        // 결과확인
        map.forEach((k,v)-> System.out.println(k+" "+v));

    }

}

 

예제02

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

public class ComputeIfAbsentTest2 {
    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.computeIfAbsent("prak", new Function<String, Integer>() {
            @Override
            public Integer apply(String s) { // 파라미터 map의 key
                System.out.println(s);
                return 58; // 리턴값 : 맵의 value
            }
        });

        //람다
        map.computeIfAbsent("hong",v -> 48);

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

    }
}

관련글 더보기

댓글 영역