问题
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:
- Obviously there could be multiple keys with the same value.
- The forEach* methods are the most efficient way to traverse Trove collections.
- You can reuse the procedures, if object allocations are a performance issue for you.
- 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