1

I have a Map implementation where I have to create a query whereby using value name field I need to return Key to that object.

One way is to use an iterator through the KeySet and check every Value, but it's not very efficient.

Time is an important factor.

Are there any interesting solutions/ libraries doing this?

Sripriya V
  • 295
  • 3
  • 8
Forin
  • 1,549
  • 2
  • 20
  • 44

2 Answers2

0

You can use BiMap from the Guava framework: https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap

Sándor Juhos
  • 1,535
  • 1
  • 12
  • 19
0

yes. using the Bidi Map :- Bidi Map

Download jar

How to use.

Example:-

BidiMap bidiMap = new DualHashBidiMap( );
bidiMap.put( "il", "Illinois" );
bidiMap.put( "az", "Arizona" );
bidiMap.put( "va", "Virginia" );
// Retrieve the key with a value via the inverse map
String vaAbbreviation = bidiMap.inverseBidiMap( ).get( "Virginia" );

// Retrieve the value from the key
String illinoisName = bidiMap.get( "il" );

Using the same approach you just need to implement the hascode() and equals() contract of a Map. Solution :-

  1. we know that HashCode is used to Store in Bucket. Assume hashcode as row number in 2-D matrix and each Row has the linked List of entry[key,value].

  2. implement the hashcode() such that for each entry[key,value] you will get different `bucket no(row no).

  3. Implement equals() method to check the equality in each bucket's entry[key,value].

  4. Complexity :- if you assign each entry[key, value] to the different bucket then SEARCHING and ADDING complexity will be o(1).

  5. please refer the below documents for better understanding of solution:-doc1 doc2

Hasnain Ali Bohra
  • 2,130
  • 2
  • 11
  • 25