LinkedHashMap打印格式化?

时间:2013-03-09 19:28:24

标签: java linkedhashmap

嘿,我有一个包含多个值的LinkedHashMap,但我正在努力以我想要的格式打印它。它将传递一个大小整数,我希望它以方形格式打印出值,如果某个键的值没有达到大小值,则在那里放置0。

说这些是hashmap中的值,首先是location,2nd是value

hashmap.put(1, 10); 
hashmap.put(2, 90); 
hashmap.put(4, 9); 
hashmap.put(7, 2); 
hashmap.put(11, 4); 
hashmap.put(14, 45); 

我希望在传递值4(高度/宽度)后按如下方式打印。

0 10 90 0
9 0  0  2
0 0  0  4
0 0  45 0

对不起,这是非常糟糕的描述,不知道怎么说更好!欢呼任何帮助。

3 个答案:

答案 0 :(得分:2)

如果给出一个整数n,则迭代整数从0到n ^ 2。在循环中,您可以使用mod来确定您是否是一行的结尾。

       if((i mod n) == 0){
           //print a new line here
       }

所以简单地编写一个从0到n ^ 2的循环,并使用该if语句知道何时中断到下一行。

答案 1 :(得分:2)

public static void printMapAsMatrix(Map<Integer, Integer> map, int size) {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            Integer v = map.get(size * i + j);
            if (v == null)
                v = 0;
            System.out.printf("%1$-5s", v);
        }
        System.out.println();   
    }
}

此解决方案填充每个单元格,使其占用5个字符。如果需要,您可以更改此项。 我们的想法是通过扫描所有单元格(0..size-1)x(0..size-1)并从地图中获取该单元格的值来创建完整矩阵。第i行和第j列应转换为key = size * i + j,因为我们必须跳过当前行中的i行和j项。不存在的项目将转换为0。

答案 2 :(得分:0)

public static void main(String[] args) {

        Map<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
        hashmap.put(1, 10);
        hashmap.put(2, 90);
        hashmap.put(4, 9);
        hashmap.put(7, 2);
        hashmap.put(11, 4);
        hashmap.put(14, 45);

        printSquare(4, hashmap);
    }

    public static void printSquare(int dimension, Map<Integer,Integer> map){
        int grid = dimension * dimension;

        for(int x = 0; x < grid; x++){

            Integer value = map.get(x);
            value = (value == null) ? 0:value;

            if(x != 0 && x % 4 == 0){
                System.out.println("\n");
                System.out.print(value);
                System.out.print("\t");
            }else{
                System.out.print(value);
                System.out.print("\t");
            }
        }
    }