开发者

Java HashMap to Matrix

开发者 https://www.devze.com 2022-12-16 18:35 出处:网络
I am facing a problem. I used the following hashmap to store some values HashMap<String, Object> hm = new HashMap<String, Object>();

I am facing a problem. I used the following hashmap to store some values

HashMap<String, Object> hm = new HashMap<String, Object>();

The object is another HashMap (yeah, you can say HashMap of HashMap). String is to store book name, and Object is again another hashmap that is to store author name and number of authors. So it can look like ( Xyz book{authname,numberOfAuthors} ). Now I want to print this hashmap as NxN matrix. 开发者_运维技巧Is there any default function out there that i can use for this? If no, then anybody can tell me any hint to do it in easy way? Because I do not want to use so many loops and if conditions (it will kill system).

Thanks!


Looks like you underused the OO potential ... You can create your own Book class and override the toString() to print all the fields ...

public class Book{
    private String bookName;
    private String authorName;
    ...
    @Override
    public String toString() {
        return String.format("%s written by %s",bookName,authorName);
    }
}

by this way your library will be something like :

Map<String, Book> myLibrary = new HashMap<String, Book>(...);

and to print all your library you will need a simple loop :

    for(Book b : myLibrary.values()) {
        System.out.println(b);
    }


Definitely no built-in function to do this.

The first thing you need to do is to figure out the unique keys in your second-level map and assign them to columns. Maybe you already know them (if they are fixed), otherwise you have to loop over all of them once and collect them in a set.

If you do have fixed keys, you should consider eliminating the second-level map, and using a Java bean class for this (the books).

If you are really going to print the matrix, you need to think about formatting, mainly column widths. Again, this can also be fixed a priori, or you can look at the data (all or sample) to figure it out.

Ignoring formatting for a moment, you can output something like CSV by then looping over the map (ideally in sorted key order), and output one line for each entry (book). In each line, you would then loop over the columns (the key list) and output each field.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号