Create Map in Java

后端 未结 5 1208
小鲜肉
小鲜肉 2020-12-13 12:06

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 unsuc

相关标签:
5条回答
  • 2020-12-13 12:15

    Java 9

    public static void main(String[] args) {
        Map<Integer,String> map = Map.ofEntries(entry(1,"A"), entry(2,"B"), entry(3,"C"));
    }
    
    0 讨论(0)
  • 2020-12-13 12:23
    Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();
    
    0 讨论(0)
  • 2020-12-13 12:35

    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?

    0 讨论(0)
  • 2020-12-13 12:37

    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);
      }
    
    0 讨论(0)
  • 2020-12-13 12:40
    Map <Integer, Point2D.Double> hm = new HashMap<Integer, Point2D>();
    hm.put(1, new Point2D.Double(50, 50));
    
    0 讨论(0)
提交回复
热议问题