create a new hashmap java code example

Example 1: new hashmap java

Map<String, String> myMap = new HashMap<String, String>() {{
        put("a", "b");
        put("c", "d");
    }};

Example 2: declare hashmap java

//remember to first import java.util.*; first

//you can swap out string or integer for other data types
Map<String, Integer> d = new HashMap<>();

Example 3: java initialize map with values in one line

Map<String, Integer> map = Stream.of(
  new AbstractMap.SimpleEntry<>("idea", 1), 
  new AbstractMap.SimpleEntry<>("mobile", 2))
  .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Tags:

Java Example