Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

java - LinkedHashMap printing formatted?

Hey I have a LinkedHashMap containing several values but I'm struggling to print it in the format I want. It will be passed a size integer, and I want it to print out the values in a square format, and if there's not a value for a certain key up to the size value to place a 0 there instead.

Say these are the values in the hashmap, first is location, 2nd is 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); 

I'd like it to print as follows after being passed the value 4 (the height/width).

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

Sorry this is really badly described, not sure how to say it any better! Cheers for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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();   
    }
}

This solution pads every cell so that it occupied 5 chars. You may change this if needed. The idea is to create the full matrix by scanning all cells (0..size-1)x(0..size-1), and fetching the value of that cell from the map. Line i and column j should be transformed to key=size * i + j, because we have to skip i lines and j items in the current line. Non existent items are converted to 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...