map get or default java code example

Example 1: getordefault java

Map<String, String> map = new HashMap<>();

    map.put("1", "Foo");
    //search for the entry with key==1, since present, returns foo
    System.out.println(map.getOrDefault("1", "dumnba"));
    //search for the entry with key==2, since not present, returns dumnba
    System.out.println(map.getOrDefault("2", "dumnba"));

Example 2: java map default value

Map<String,String> data=new HashMap<>();
String someValue=data.getOrDefault("test","");//gets the value of "test" or "" if it does not exist

Tags:

Java Example