-1

I have a generic Map which is defined thus

Map<Integer, Book> bookCollection

The Integer is the book ID and the Book is obviously a Book object. The Book object has a member called publicationYear.

How do I sort the Map so that its Book objects are in order by the Book's publicationYear member. So, if I iterate through the sorted map, the oldest book appears first up to the newest book.

At the moment, the Map is randomly sorted.

John Steed
  • 599
  • 1
  • 12
  • 31

2 Answers2

1

the publicationYear has to be part of the key. to sort based on that.

MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66
  • Thanks, but I need the key to be the book ID for other functionality. – John Steed May 18 '14 at 14:11
  • @DamienFenton You cannot sort a map if the sort key is not part of the map key. Either include year into the map key or use a different data structure. – Aleks G May 18 '14 at 14:14
1

One solution to this sort of problem is to write your own data structure that uses a two or more standard data structures to implement the messy details.

For example, you could use a HashMap<Integer, Book> to allow rapid look-up by Id. You could also have a TreeSet<Book> in the required order. If it is not the case that Book is Comparable with the key you need for this, use a Comparator<Book> to create the TreeSet.

Most methods for the composite data structure will be two or three lines long. The fact that the two underlying structures exist and are being kept consistent is hidden from the rest of the program, which just accesses the composite structure.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75