• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Sorting ArrayList of Hashtables

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have an ArrayList of Hashtables that I need to sort. Ideally I would like to specify which key-value pair to sort against. What would be the best way to implement this?
Thanks in advance,
Tim Harrison
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, just on general principle - Hashtables are evil. Use HashMaps instead. This applies to all the legacy collection classes. Use ArrayList and Iterator rather than Vector and Enumeration. Peter den Haan's last post here nicely summarizes why. Thanks.
For your question, you probably will want to do something like this:

Here I assume that each List will contain Maps (such as HashMap or Hashtable) which will contain the expected key values - and that throwing ClassCastException or NullPointerException are appropriate if these assumptions are not met. Also this is set up to sort by many different keys. Each sort may not be as fast as you'd like - the problem is that you're going to be invoking the get() method a lot of times for each search. It would probably be faster to replace the Maps with some other custom class which caches the required search criteria in an instance field, rather than having to look it up in a table each time. But then you probably need a separate field for each key/value you want to be able to search on, and a separate Comparator to use this field. This may be worthwhile to set up, but you lose the ability to sort on an arbitrary key. So it depends what your requirements are.
 
I just had the craziest dream. This tiny ad was in it.
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic