Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Java Datastructure to store key Value Pair [duplicate]

Tags:

java

android

Possible Duplicate:
Java Hashmap: How to get key from value?
Bi-directional Map in Java?

I want a key value data structure to use for Android App. I can use Map<K,V>, but in Map I can't get key for particular Value.

Is there any good Java data structure using which I can retrieve key by value and vice-versa.

like image 600
Sharanabasu Angadi Avatar asked Jan 30 '13 09:01

Sharanabasu Angadi


People also ask

Which data structure in Java allows duplicate keys?

One of these data structures is called Multimap and it allows us to store duplicate keys in a more elegant fashion.

Which data structure will you choose to hold duplicate values?

For just storing simple values, you should use an implementation of the List<E> interface. Depending on your use either an ArrayList<E> or LinkedList<E> will do what you need. Another option would be a Map<K, V> (it's implementation HashMap ). This will allow you to save duplicate values under unique keys.

Which collection can store duplicate keys in Java?

You can use Multimap it supports duplicate keys but it also support duplicate keys and value pairs. Best solution for you is use Multimap and check if value already exist then dont add it.

Which data structure is used for key value pair?

key-value store, or key-value database is a simple database that uses an associative array (think of a map or dictionary) as the fundamental data model where each key is associated with one and only one value in a collection. This relationship is referred to as a key-value pair.


1 Answers

You can use Map with entrySet and Map.Entry class to iterate and get both keys and values even if you don't know any of the keys in the Map.

Map <Integer,String> myMap = new HashMap<Integer,String>();

Iterator<Entry<Integer, String>> iterator = myMap.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<Integer,String> pairs = (Map.Entry<Integer,String>)iterator.next();
    String value =  pairs.getValue();
    Integer key = pairs.getKey();
    System.out.println(key +"--->"+value);
}
like image 186
Saumik Chaurasia Avatar answered Oct 29 '22 17:10

Saumik Chaurasia