Search code examples
javahashmaptrove4j

TIntObjectHashMap - get Key for given value


How to get the key from Trove TIntObjectHashMap for a value that exists and been found in the map ??

if(map.containsValue(source)) {
        for (Entry<Integer, String> entry : map.entrySet()) { // entrySet() is not recognized by Trove? and i can not find any corresponding method ??
            if (entry.getValue().equals(source)) {
                entry.getKey();
        }
    }
}

Solution

  • I would do something like this:

    TIntObjectMap<String> map = new TIntObjectHashMap<>();
    map.put( 1, "a" );
    map.put( 2, "b" );
    
    AtomicInteger found = new AtomicInteger( -1 );
    map.forEachEntry( new TIntObjectProcedure<String>() {
        @Override
        public boolean execute( int key, String value ) {
            if ( value.equals( "a" ) ) {
                found.set( key );
                return false;
            }
            return true;
        }
    } );
    System.out.println( "Found: " + found.get() );
    

    Things to remember:

    1. Obviously there could be multiple keys with the same value.
    2. The forEach* methods are the most efficient way to traverse Trove collections.
    3. You can reuse the procedures, if object allocations are a performance issue for you.
    4. If "-1" (or whatever else) is a valid key for the map, you could use another AtomicBoolean to indicate whether or not you found the value.