Note that there are some explanatory texts on larger screens.

plurals
  1. PORetrieving key from value in hashtable in Java
    primarykey
    data
    text
    <p>I am a new bie to the world of collections but still, In my below class I have hashtable as I have to choose hashtable and I want to retrieve the key basis on the value , below is my class..</p> <pre><code>public class KeyFromValueExample { public static void main(String args[]) { Hashtable table = new Hashtable(); table.put("Sony", "Bravia"); table.put("Samsung", "Galaxy"); table.put("Nokia", "Lumia"); System.out.println("does hash table has Lumia as value : " + table.containsValue("Lumia")); System.out.println("does hash table Lumia as key : " + table.containsKey("Lumia")); //finding key corresponding to value in hashtable - one to one mapping String key= null; String value="Lumia"; for(Map.Entry entry: table.entrySet()){ if(value.equals(entry.getValue())){ key = entry.getKey(); break; //breaking because its one to one map } } System.out.println("got key from value in hashtable key: "+ key +" value: " + value); //finding key corresponding to value in hashtable - one to many mapping table.put("HTC", "Lumia"); Set keys = new HashSet(); for(Map.Entry entry: table.entrySet()){ if(value.equals(entry.getValue())){ keys.add(entry.getKey()); //no break, looping entire hashtable } } System.out.println("keys : " + keys +" corresponding to value in hash table: "+ value); </code></pre> <p>Output :-</p> <pre><code>does hash table has Lumia as value : true does hash table has Lumia as key : false got key from value in hashtable key: Nokia value: Lumia keys : [Nokia, HTC] corresponding to value in hash talbe: Lumia </code></pre> <p>Now please advis is there any other better way to achieve the same thing, Please advise if other better alternatives are there.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload