Java Collection How to - Get default value from Map








Question

We would like to know how to get default value from Map.

Answer

import java.util.HashMap;
import java.util.Map;
/*from  w w w .j a  v a2 s  . c  o  m*/
public class Main {

    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();

        for (int i = 0; i < 10; i++) {
            map.putIfAbsent(i, "val" + i);
        }

        map.forEach((id, val) -> System.out.println(val));

        System.out.println(map.getOrDefault(42, "not found"));      // not found
    }

}

The code above generates the following result.