views:

352

answers:

2

Hi all gurus!

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!

+2  A: 

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.

Thilo
...and the loops and conditions can't possibly "kill the system". Write it as @Thilo suggests and only then, if you see performance problems, start to worry about performance. Even if there were a built-in way, that way would be using the same loops and conditions internally, so performance would be roughly identical to the obvious hand-rolled approach.
Carl Manaster
+2  A: 

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);
    }
wj