103

I'd like to create a map that contains entries consisting of (int, Point2D)

How can I do this in Java?

I tried the following unsuccessfully.

HashMap hm = new HashMap();

hm.put(1, new Point2D.Double(50, 50));
Kevin Meredith
  • 39,688
  • 61
  • 199
  • 355

6 Answers6

143
Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
hm.put(1, new Point2D.Double(50, 50));
hd1
  • 32,598
  • 5
  • 75
  • 87
  • 12
    You also must do `import java.util.Map; import java.util.HashMap;` or `import java.util.*;` – Max Apr 06 '17 at 16:49
26

Java 9

public static void main(String[] args) {
    Map<Integer,String> map = Map.ofEntries(entry(1,"A"), entry(2,"B"), entry(3,"C"));
}
Durgpal Singh
  • 9,789
  • 4
  • 35
  • 48
25

There is even a better way to create a Map along with initialization:

Map<String, String> rightHereMap = new HashMap<String, String>()
{
    {
        put("key1", "value1");
        put("key2", "value2");
    }
};

For more options take a look here How can I initialise a static Map?

webdizz
  • 690
  • 6
  • 10
12

With the newer Java versions (i.e., Java 9 and forwards) you can use :

Map.of(1, new Point2D.Double(50, 50), 2, new Point2D.Double(100, 50), ...)

generically:

Map.of(Key1, Value1, Key2, Value2, KeyN, ValueN)

Bear in mind however that Map.of only works for at most 10 entries, if you have more than 10 entries that you can use :

Map.ofEntries(entry(1, new Point2D.Double(50, 50)), entry(2,  new Point2D.Double(100, 50)), ...);
dreamcrash
  • 40,831
  • 24
  • 74
  • 100
10
Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();
Achrome
  • 7,533
  • 14
  • 33
  • 45
3

I use such kind of a Map population thanks to Java 9. In my honest opinion, this approach provides more readability to the code.

  public static void main(String[] args) {
    Map<Integer, Point2D.Double> map = Map.of(
        1, new Point2D.Double(1, 1),
        2, new Point2D.Double(2, 2),
        3, new Point2D.Double(3, 3),
        4, new Point2D.Double(4, 4));
    map.entrySet().forEach(System.out::println);
  }
f.khantsis
  • 2,986
  • 3
  • 45
  • 58