TIntObjectHashMap - 获取给定值的密钥 [英] TIntObjectHashMap - get Key for given value

查看:392
本文介绍了TIntObjectHashMap - 获取给定值的密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Trove TIntObjectHashMap获得一个存在于地图中的值?

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


推荐答案

我会这样做:

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. 显然,可能有多个键具有相同的值。
  2. forEach *方法是遍历Trove集合的最有效方式。
  3. 如果对象分配对您来说是性能问题,您可以重复使用这些过程。
  4. 如果-1(或其他)是映射的有效键,则可以使用另一个AtomicBoolean指示您是否找到该值。
  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.

这篇关于TIntObjectHashMap - 获取给定值的密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆