Search code examples
javasortinggroupingstore

How to store, sort and group items (list/set/map) in java?


Given such data

UserID, MovieType , year 
1, 2, 2000
1, 3, 2000 
1, 2, 2006
2, 3, 2010
2, 4, 2011
2, 3, 2002
1, 2, 2010

What are the best option to store it in java , such that I can sort it according to first column , then second column then third ?

UserID, MovieType , year 
1, 2, 2000
1, 2, 2006
1, 2, 2010
1, 3, 2000 
2, 3, 2002
2, 3, 2010
2, 4, 2011

And then group them by user ID and Movietype

UserID, MovieType , movies seen per year  
1, 2, 3
1, 3, 1 
2, 3, 2
2, 4, 1

Solution

  • For a very specific solution, you could have a Map<Integer, Map<Integer, Integer>>.

    The first Map stores UserIDs to a map that stores MovieTypes to MoviesSeenPerYear.

    If you use a TreeMap as the underlying types, everything will automatically be numerically sorted.

    This will not be very flexible, though - for example, it would be difficult if you wanted to re-sort by MovieType instead of UserId.


    In response to your comment:

    You will have 2 main limitations:

    1. All of the Java collections classes are based on int sizes (same as the Java's array indexer), which have a maximum size of just under 2^31-1, or 2,147,483,647 - or just over 2 billion entries.
    2. Memory limitations of your JVM / machine.

    If you're looking at working with this much data, and would like more flexible sorting requirements, you'd be well advised to use an actual database - either one of the standard ones, or even a JVM-embedded one like H2 or Apache Derby.