TIntObjectHashMap - get Key for given value

大城市里の小女人 提交于 2019-12-12 04:49:10

问题


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();
        }
    }
}

回答1:


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.



回答2:


You can try in this way

TIntObjectHashMap<String> map = new TIntObjectHashMap<>();
map.put(1, "a");
map.put(2, "b");
//convert   TIntObjectHashMap to java.util.Map<Integer,String>
Map<Integer, String> utilMap = new HashMap<>();
for (int i : map.keys()) {
    utilMap.put(i, map.get(i));
}
Integer key=null;
if (map.containsValue("a")) {
    for (Map.Entry<Integer, String> entry : utilMap.entrySet()) { // issue solved
         if (entry.getValue().equals("a")) {
            key=entry.getKey();
           }
      }
}
System.out.println(key);

Out put:

1


来源:https://stackoverflow.com/questions/26120131/tintobjecthashmap-get-key-for-given-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!