2

I have some code where I read an object off a JMS topic (unfortunately I cannot share the actual code, so I will use a hypothetical example) - let's assume the object is Employee (firstName, lastName, postCode, email, etc), and I insert the employee object into a Map where the key is the email address for quick retrieval. However, my requirements are likely to change and I may also need to look up by firstName. So now I have to maintain two maps, one keyed by email and one keyed by firstName. Then if I get a new requirement, I have to maintain an additional map, and so on and so forth - nightmare code ensues.

I had a look at the Guava BiMap, which is great if you only have 2 fields and both of them are unique, but I was wondering if there is a Util out there (Apache Commons Collections, Guava Collections, any other) that will give me this out of the box - essentially, I want something like a List which I can very simply insert to and remove from, and it will handle several backing maps for me so that finding elements by a given field is roughly O(1). My current implementation is to use Java 8 parallelStream and filter, but this won't scale once my list grows (which it potentially could up to a few million entries).

The only other option I have come up with so far is to use an in-memory database such as HSQLDB, index every column, and use some simple SQL to retrieve my values. I believe this will work but has a fair amount of overhead maintaining a schema, writing queries etc.

TL;DR: Is there a collection type in a lilbrary that looks like List but that can give me O(1) retrieval based on any field in the objects?

Matt
  • 3,303
  • 5
  • 31
  • 53
  • if you want access time with O(1) you have the Map, check this post http://stackoverflow.com/questions/1237581/need-a-java-map-table-with-multiple-keys-to-one-value-value-is-commonly-altered – Amer Qarabsa Oct 03 '16 at 11:41
  • Creating an index for each column in your DB is essentially the same as maintaining one map per field, which you could "automate" in pure Java by using reflection. The caveat is of course that memory usage may become an issue, depending on the size of your dataset. – assylias Oct 03 '16 at 11:50
  • 1
    http://stackoverflow.com/questions/2501449/multiple-indexes-for-a-java-collection-most-basic-solution ... apparently no easy solutions. – Petr Janeček Oct 03 '16 at 11:53

0 Answers0