来自 X-Y 坐标图的 Java 字符串

标签 java string dictionary coordinates coordinate-systems

我有一个 map ,其中 Coords 定义如下:

class Coords {
        int x;
        int y;
        public boolean equals(Object o) {
            Coords c = (Coords)o;
            return c.x==x && c.y==y;
        }
        public Coords(int x, int y) {
            super();
            this.x = x;
            this.y = y;
        }
        public int hashCode() {
            return new Integer(x+"0"+y);
        }
    }

(不是很好,我知道,请不要取笑我。)我现在如何创建一个字符串,其中的字符是从此映射映射的,例如:

Map<Coords, Character> map = new HashMap<Coords, Character>();
map.put(new Coords(0,0),'H');
map.put(new Coords(1,0),'e');
map.put(new Coords(2,0),'l');
map.put(new Coords(3,0),'l');
map.put(new Coords(4,0),'o');
map.put(new Coords(6,0),'!');
map put(new Coords(6,1),'!');
somehowTransformToString(map); //Hello !
                               //      !

谢谢,
艾萨克·沃勒
(注意 - 这不是家庭作业)

最佳答案

  1. 创建一个可以先按 y 然后按 x 对坐标进行排序的比较器:

    int d = c1.y - c2.y;
    if (d == 0) d = c1.x - c2.y;
    return d;
    
  2. 创建一个排序的 map :

    TreeMap<Coords, Character> sortedMap = new TreeMap(comparator);
    sortedMap.putAll(map); // copy values from other map
    
  3. 按顺序打印 map 的值:

    for (Character c: map.values()) System.out.print(c);
    
  4. 如果你需要换行:

    int y = -1;
    for (Map.Entry<Coords, Character> e: map.entrySet()) {
        if (e.y != y) {
            if (y != -1) System.out.println();
            y = e.y;
        }
        System.out.print(c);
    }
    

关于来自 X-Y 坐标图的 Java 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/907292/

相关文章:

java - 以内存有效的方式计算 MongoDB(Java 驱动程序)中的唯一对象

java - 在 JPQL 中查询获取过去 X 个月的数据

java - 为什么String是一个类?

python - 在 Python 字典中搜索匹配键

python - 将字典分组为可能的最小键值对集

java - 并行调用mysql数据库时的注意事项

java - Liferay:操作阶段后的 .jsp 错误且值不正确

java - 循环遍历字符串 - 输入作为参数 [java]

php - 使用字符串 - PHP

javascript如何动态地将子字典附加到父字典