How to create a map with key type point (x, y) and value type string in Java

1 Answer

0 votes
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // Getters
    public int getX() { return x; }
    public int getY() { return y; }

    // Override equals and hashCode
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point)) return false;
        Point point = (Point) o;
        return x == point.x && y == point.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }

    // Override toString for easy printing
    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }

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

        map.put(new Point(2, 7), "A");
        map.put(new Point(3, 6), "B");
        map.put(new Point(0, 0), "C");

        // Print x and y separately
        for (Map.Entry<Point, String> entry : map.entrySet()) {
            Point key = entry.getKey();
            String value = entry.getValue();
            System.out.println("x: " + key.getX() + ", y: " + key.getY() + " => " + value);
        }
    }
}



/*
run:
  
x: 0, y: 0 => C
x: 3, y: 6 => B
x: 2, y: 7 => A
  
*/


 



answered Aug 10, 2025 by avibootz
...