manikanta
manikanta

Reputation: 8500

Better data structure for faster reads in Map of Map of Map of Lists

I've a scenario where I need to store the map of map of map of list of data hierarchy for processing in memory. And, currently I m thinking to implement the data structure as

Map<Integer, Map<String, Map<Integer, List<String> > > >

and the concretes types are,

HashMap<stdIdInt, HashMap<libraryNameStr, HashMap<topicIdInt, ArrayList<bookNameStr> > > >

As I do not need to maintain any particular order, I m also thinking to replace List with Set (HashSet) which potentially can increase the performance.

Though I've tried till now, I also think using Google' Guava Multimap is a viable alternate, but I m not sure.

Background: I need to store the details of each student's id & their interested book names information categorised by their topic type which will be further organised by library names. I need to process the data & display book names mostly by student id and other times by library name & topic type. And once the book name is shown to the user, I need to delete that entry from the book names list.

The data structure needs to hold & process thousands of entries at high rate and will hold the data for longer time.

Please suggest an approach or another data structure for faster processing, and about the type of the data structure/collection class and their usage combination.

(please note that the scenario I described above is not exact case, but I tried my best to abstract the complexity of the data hierarchy)

Upvotes: 0

Views: 549

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340693

I think you are missing a lot of abstractions here. The rule of thumb is: every time a collection holds another collection, intermediate object should be introduced.

In your case this is my suggested OO design:

class Student {
    private int id;
    private Map<Integer, Library> libraries;
    private getLibrary(int id) {return libraries.get(id);}
}

class Library {
    private int id;
    private Map<Integer, Topic> topics;
    private getTopic(int id) {return topics.get(id);}
}

class Topic {
    private int id;
    private Map<Integer, Book> books;
    private getBook(int id) {return books.get(id);}
}

class Book {
    private int id;
    private String name;
}

And usage:

Map<Integer, Student> students = //...
students.get(6).getLibrary(5).getTopic(4).getBook(3)

Of course this code needs a lot of further improvements. E.g. you shouldn't need more than one . in a line. But it's already much more readable than:

students.get(6).get(5).get(4).get(3)

Upvotes: 3

Related Questions