Best Java Datastructure to store key Value Pair [duplicate] - java

This question already has answers here:
Closed 10 years ago.
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.

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

Use Google Guava BiMap
How to use Guava Libraris in Android is here

The best data structure would be Java HashMaps check this link you can use the get(Object key) method

Related

Need to sort alphanumeric keys of a map [duplicate]

This question already has answers here:
How can I sort Map values by key in Java?
(17 answers)
Closed 6 years ago.
Lets say, I have a map as Map<String, String> data = new HashMap<String, String>();
I have following keys of this map
{benefits7,benefits11,benefits1,benefits10,benefits15};
And I need it to sort these keys as following:
{benefits1,benefits7,benefits10,benefits11,benefits15}
Can anyone help please?
Can't you use SortedMap instead HashMap?
This way if you iterate over the map by using entrySet or KeySet it will return your values sorted by its key.
By default it use the natural ordering for your key's class (String in your example), and this behaviour seems enough for your requirements
Here is the SortedMap API
Can you try this ?
Map<String, String> data = new HashMap<String, String>();
Set<String> keys = data.keySet();
Set<String> sortedKeys = Collections.sort(keys);
You can use a list to sort the keys. If you need to have order in your map, then you should not use a HashMap as it doesn't care about order.
Use a linked hash map instead. So, you could have an ordered list of keys:
List<String> keys = new ArrayList<String>(data.keySet());
Collections.sort(keys);
If you want to iterate over the map according to the order of your keys, then use a java.util.LinkedHashMap, instead of a HashMap. But you would have to put elements according to the explicit order as shown above.

Alternative for hashmap [duplicate]

This question already has an answer here:
Java: Get hashmap value [closed]
(1 answer)
Closed 6 years ago.
I have a hashmap which has several values and it override the same keys, is there any solution for this? this is my Hashmap
HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Jack","John");
meMap.put("Jack","Jacob");
it will override the first one.
You can use get function: meMap.get("Color3");. You can access to different methods of maps in Java here:
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
A Map is a Key - Value store, meaning that you access values in the Map by specifying its Key. So you would do:
meMap.get("Color3");
You have to use get() for single element:
Toast.makeText(context, map.get("Color3"), Toast.LENGTH_SHORT).show();
You can not have multiple values for one key in HashMap.
If you need to store multiple values for same key then you should use map insted of HashMap.
Map has combination of Key and value. If you want a value, you have to call it's key.
System.out.println(meMap.get("Color3"));
Resource Link:
Class HashMap
From your comment,it seems you want to store multiple values for a single key.In that case you can store your values in a List and then add that list to the map,as shown below:
HashMap<String, List<String>> meMap=new HashMap<String, List<String>>();
List<String> lst=new ArrayList<String>();//List to store colors
lst.add("Red");
lst.add("Blue");
lst.add("Green");
lst.add("White");
//add the key and list to map
meMap.put("Color",lst);
//to get the value at 3rd position,use get(2),as index starts from 0.
System.out.println(meMap.get("Color").get(2));

Retrieve key of Map by index [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Bi-directional Map in Java?
How can I retrieve key of Map by index when keys are not numeric and unordered ?
For example :
Map<String, Integer> test = new TreeMap<String, Integer>();
test.put("a", 1);
test.put("b", 2);
test.put("z", 3);
test.put("m", 4);
I want to get z if I have index 2 or a if I have index 0.
I know I can do dirty loop with increment to get it but is there another smart way to do it ?
What makes this a bit confusing is whether you're referring to the index based on the order the item is added, or based on the natural ordering of the key (eg: alphabetical)
You can obtain the list of may keys using map.keySet() but there's no guarantee the key set will be in the order which you add it in
You can use TreeMap instead of HashMap if you want to keep your data in some kind of ordering (eg: alphabetical ordering). If you prefer other way of ordering you can implement your own comparator

How to get the key and value from hashmap in the order they have been put int map [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
ordered map implementation
I am using the hashmap to store the values as follows -
Map<String,String> propertyMap=new HashMap<String,String>();
propertyMap.put("Document Type", dataobject.get("dDocType"));
propertyMap.put("Document Title", dataobject.get("dDocTitle"));
propertyMap.put("Revision Label", dataobject.get("dRevLabel"));
propertyMap.put("Security Group", dataobject.get("dSecurityGroup"));
After that i am getting the hashmap key and value in a List
documentProperties = new ArrayList(propertyMap.entrySet());
But when i iterate over the List i am not getting the key and values in the order i have put it into the map..
Is there is anyway by which i can get the values in the Order i am putting it into the map.
Thanks
I believe what you are looking for is LinkedHashMap.
This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
By the why, why the need for a separate ArrayList? You can directly iterate over Map.entrySet:
for (final Map.Entry<String, String> entry : propertyMap.entrySet()) {
...
}
propertyMap.entrySet() you get results as Set. Set is un-ordered.
new ArrayList(propertyMap.entrySet()); constructs a list with the order you have in Set (which may not be the order you have put into map).
If you are looking for order map, you may use LinkedHashMap
Here is interesting discussion on this topic.
You have to use LinkedHashMap. For more details Please check this question and answer given by Michael
Try this..
for(Map.Entry<String, String> m : map.entrySet()){
// Use m.getKey() to get the Key.
// Use m.getValue() to get the Value.
}

Retrieving Key from the Hash Map

I'm new to Java. I implemented a Hash Map as shown below.
In a particular scenario I wanted to retrieve the key using values of the key.
For Eg: If user enters "Dravid", then I need to retrieve "2" from the Hash Map.
And I want to use only one hash map to implement this.
Can anyone help me with this?
HashMap<String,String> streetno=new HashMap<String,String>();
streetno.put("1", "Sachin");
streetno.put("2", "Dravid");
streetno.put("3","Sehwag");
streetno.put("4", "Laxman");
streetno.put("5", "Kohli");
Short version, so there is something to implement left for you:
Iterate over all entries of the map and compare your search string to the value of the entry. If it matches, return the key.
With a standard HashMap, the only thing you can do is iterate over the entries of the map until you find one that has the value that you are looking for and then return the key for that.
HashMap is made to quickly and efficiently lookup a value if you know the key, but not the other way around. There are some libraries that have maps that allow you to lookup the value by key as well as the other way around. Google Guava for example has a BiMap that supports this.
Using Guava's HashBiMap, you could do this:
BiMap<String, String> map = HashBiMap.create();
map.put("1", "Sachin");
map.put("2", "Dravid");
map.put("3", "Sehwag");
map.put("4", "Laxman");
map.put("5", "Kohli");
String key = map.inverse().get("Dravid");
To do this, you would need to use a bi-directional hashmap. Consider using the Apache Commons implementation.
Without it, you'd need to iterate over all the key / value pairs in the map and test for when the value equals "Dravid", then return the key. Like so:
for (Entry<String, String> pair : streetno.entrySet()) {
if (pair.getValue().equals("Dravid")) {
System.out.println("Found Dravid at key: " + pair.getKey());
}
}
You can do any of the above said answers, its also better to add this check before proceeding to the actual logic.
if(streetno.containsValue("Dravid")){
// do logic
}
else
System.out.println("Not found");

Categories