Is there any way to get a key associated with a known value in a map? Normally you know the key and you want to get the value, but I want to do the opposite, going from value to key. Is it possible?
Yes, you have to iterate over the values in the map and then store each key in a list:
for (Map.Entry<K,V> entry : map.entrySet()) {
V value = entry.getValue();
if (value.equals(someTargetValue) {
// add key (entry.getKey()) to list
}
}
Or you could use a bidirectional map, though do note:
This map enforces the restriction that there is a 1:1 relation between keys and values, meaning that multiple keys cannot map to the same value.
Well, I am not an expert on Google Project LambdaJ, but it certainly offers a few cool alternatives.
Supposing you have a map with all the days of the month:
month.put(1,"Monday");
month.put(2,"Tuesday");
month.put(3,"Wednesday");
...
Then we could easily achieve what you want like this:
Set<Integer> result = with(month).retainValues(is("Friday")).keySet();
Or even a few more interesting searches like:
Set<Integer> result = with(month).retainValues(anyOf(is("Monday"),is("Friday"))).keySet();
Without iterating all the keys looking for the value you can use an Apache Commons BidiMap
A Map is a mathematical entry which doesn't imply that a reverse mapping is possible. That said you might be able to create a "reverse" mapping if every mapped value is unique. Naturally, you'll have to encapsulate all the data manipulations in methods that update both Maps appropriately.
Map<Key, Value> normal;
Map<Value, Key> reverse;
If every mapped value is not unique, then you need to create a reverse mapping of a value to a list of keys.
Map<Key, Value> normal;
Map<Value, List<Key>> reverse;
Finally, if you don't care about fast access, you can iterate over the entire Map looking for Values. Since you'll need both the Value and the Key, it is probably best to iterate over the Map.Entry items.
Value searchingFor = ...;
Map<Key, Value> normal;
List<Key> keys = new ArrayList<Key>();
for (Map.Entry<Key, Value> entry : normal.entrySet()) {
if (entry.getValue().equals(searchingFor)) {
keys.add(entry.getKey());
}
}
The technique you choose to use will depend heavily on whether it is better to trade speed for memory footprint. Generally having an extra Map is faster due to the hashing being done on the Value(s), but costs extra memory. Having a loop over the Map.Entry(s) is slower, but costs less memory.
Here they already talked about Bidirectional maps. Nowadays, Guava (https://github.com/google/guava) offers a nice BiMap that you can use for that purpose:
https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap
Related
below is my code...
Map<Integer, String> MyType = sessionInfo.getType();
//{2=somename}
I am trying to get key from value...without running any loops....is it possible?
MyType.get("somename") // should output 2`
It's not easy to get key from value in Hashtable or HashMap, as compared to getting value from key, because Hash Map or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. infact Map allows same value to be mapped against multiple keys inside HashMap, Hashtable or any other Map implementation.
String key= null;
String value="somename";
for(Map.Entry entry: MyType.entrySet()){
if(value.equals(entry.getValue())){
key = entry.getKey();
break; //breaking because its one to one map
}
}
I would encourage running a loop for simplicity. It most likely will not slow down your program a noticeable amount.
However, if you must not run a loop, Google's Guava library has a BiDirectional Map Collection called BiMap that can be (found here). The map works both ways and is guaranteed to be synchronized at all times. I also am assuming that you have unique values in your map. If you do not, duplicate values will not have a specific key to link to.
BiMap<String, Integer> biMapInversed = biMap.inverse(); // how to get inverted map
Again, I wouldn't encourage this unless absolutely necessary. Looping through will work perfectly fine in most cases.
Taken from this SO answer
If you choose to use the Commons Collections library instead of
the standard Java Collections API, you can achieve this with ease.
The BidiMap interface in the Collections library is a
bi-directional map, allowing you to map a key to a value (like normal
maps), and also to map a value to a key, thus allowing you to perform
lookups in both directions. Obtaining a key for a value is supported
by the getKey() method.
There is a caveat though, bidi maps cannot have multiple values mapped
to keys, and hence unless your data set has 1:1 mappings between keys
and values, you cannot use bidimaps.
This is not possible. You need to consider the value may be duplicated in map.
Ex, How do you deal with {2=somename} and {5=somename}
You still need to use a for loop to check value and get key and decide to break or go on when value is matched.
If you're sure that your values are unique you can iterate over the entries of your old map .
Map<String, Character> myNewHashMap = new HashMap<>();
for(Map.Entry<Character, String> entry : myHashMap.entrySet()){
myNewHashMap.put(entry.getValue(), entry.getKey());
}
Alternatively, you can use a Bi-Directional map like Guava provides and use the inverse() method :
BiMap<Character, String> myBiMap = HashBiMap.create();
myBiMap.put('a', "test one");
myBiMap.put('b', "test two");
BiMap<String, Character> myBiMapInversed = myBiMap.inverse();
Situation:
I have a Map, a TreeMap to be more exact that looks like
TreeMap<String, Integer>
I have to be able to sort it on either the key OR the value in an ascending OR descending way. The result must be a Map like
Map<String, Integer>
Not an ArrayList or anything like that because the rest (read: allot) of my code won't work anymore. I've searched but couldn't find anything that suits my needs. Is this even possible? Double values may not be lost.
If you use two BiMaps which each back each other, then you effectively have one map.
Somthing like:
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
private BiMap<Integer, String> localid = HashBiMap.create();
private BiMap<String, Integer> inverse = localid.inverse();
you can treat each reference, localid & inverse, as their own map, but changes to one are reflected in the other. The only slight downside is that now both the keys and values must be unique, as the values of one are the keys of the other. For most cases this is not a problem.
For sorting it, you can at any time make a local copy which is a treeMap, and that imposes an ordering. E.g.
ImmutableMap.copyOf(Maps.newTreeMap(bimap))
Now if you are never making changes to your map, this will provide a sorted view, and you can do it by either.
EDIT: A TreebasedTable has two keys for each value, and you can sort either keyset with a comparator. I am not sure that this is exactly what you need, here as the keysets are independent, but you might be able to refactor your code slightly to make this a viable solution.
If the map is small and iterating over it is an infrequent operation, one solution would be to just use a HashMap (for lookup speed) and then sort the entries every time you iterate.
Another solution, if you do these iterations frequently compared to direct map lookups, and if the values (and not just the keys) are unique, would be to maintain two sorted maps, one <String, Integer> and one <Integer, String>.
Guava has the concept of BiMap. Is that what you're looking for?
A TreeMap's keys are sorted by it's comparable.
Try a SortedMap
A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of SortedSet.)
I have a hash map. Multiple keys have same value. What is the best way to find the
keys for repeated Values without iterating. ?
Reading this documentation it feels there is no function for it.
NOTE: Key | Value pair are of Int type
One way or the other, you will end up iterating the collection. The iteration may be hidden from view in some library, but it would necessarily be there.
You can easily write a simple method that does what you need:
public static <K,V> Set<K> keysOfDupValues(Map<K,V> m) {
Set<K> res = new HashSet<K>();
Map<V,K> seen = new HashMap<V,K>();
for (Map.Entry<K,V> e : m.entrySet()) {
V v = e.getValue();
K k = e.getKey();
if (seen.containsKey(v)) {
res.add(k);
res.add(seen.get(v));
} else {
seen.put(v, k);
}
}
return res;
}
Demo on ideone.
There is no way to find all the keys for a value without iterating on the Map in standard JDK API.
You can use the Guava library, either by :
using Maps.filterValues that returns entries whose values satisfy a Predicate
converting to a Guava Multimap and use Multimaps.invert
using a BiMap.
It's really not possible. The very implementation of method containsValue(), in the superclass java.util.AbstractMap iterates through the values.
So, you'll have to itarate through the values to achieve that.
You can take a look at the implementation of containsValue() to have a hint on how to do that.
If you get that map read made from code you don't have control on, then you have no other choice but to iterate on the map.
In any case, you can avoid the issue of doing several iterations by building a reverse map, which will boil down to a multimap, but since there is no specific class definition for that pattern in Java, you will have to build it using a map and lists.
Each time you need to include a new pair <k,v> in your original map, you also include the reverse pair <v,k> in your reverse map. If v as a key (ie. the original value) doesn't yet exist in the reverse map, you map it to a list solely containing k as the value (ie. the original key). If the key v already exists in the reverse map, then you simply push the value k to the existing list.
When you need to know which keys map to a given value in your original map, you query for the value in the reverse map, and get the list of keys.
The Java tutorial on maps includes a section on implementing multimaps using maps.
This solution should be very effective if you have control on the map creation process. However, if the map is created and regularily updated by some outside mechanism, it will be of little gain.
If you can only control the creation of the map, but not its update, you could implement a new class exposing the Map interface, which internally holds the reverse map as well and update it when a new pair is inserted/removed, or support a notification mechanism to let your code know the map has been changed and how.
Try change
File newxmlfile = new File(Environment.getExternalStorageDirectory()
+ ts);
to
File newxmlfile = new File(Environment.getExternalStorageDirectory()
+ "/"+ts);
This question is kind of already posted here:
How to convert Map<String, String> to Map<Long, String> using guava
I think the answer of CollinD is appropriate:
All of Guava's methods for transforming and filtering produce lazy
results... the function/predicate is only applied when needed as the
object is used. They don't create copies. Because of that, though, a
transformation can easily break the requirements of a Set.
Let's say, for example, you have a Map<String, String> that contains
both "1" and "01" as keys. They are both distinct Strings, and so the
Map can legally contain both as keys. If you transform them using
Long.valueOf(String), though, they both map to the value 1. They are
no longer distinct keys. This isn't going to break anything if you
create a copy of the map and add the entries, because any duplicate
keys will overwrite the previous entry for that key. A lazily
transformed Map, though, would have no way of enforcing unique keys
and would therefore break the contract of a Map.
This is true, but actually I don't understand why it is not done because:
When the key transformation happen, if 2 keys are "merged", a runtime exception could be raised, or we could pass a flag to indicate to Guava to take any value of the multiple possible values for the newly computed key (failfast/failsafe possibilities)
We could have a Maps.transformKeys which produces a Multimap
Is there a drawback I don't see in doing such things?
As #CollinD suggests, there's no way to do this in a lazy way. To implement get, you have to convert all the keys with your transformation function (to ensure any duplicates are discovered).
So applying Function<K,NewK> to Map<K,V> is out.
You could safely apply Function<NewK,K> to the map:
V value = innerMap.get( fn.apply(newK) );
I don't see a Guava shorthand for that--it may just not be useful enough. You could get similar results with:
Function<NewK,V> newFn = Functions.compose(Functions.forMap(map), fn);
Is it possible to have multiple values for the same key in a hash table? If not, can you suggest any such class or interface which could be used?
No. That's kind of the idea of hash tables.
However, you could either roll your own with a Map<YourKeyObject, List<YourValueObject>> and some utility methods for creating the list if it's not present, or use something like the Multimap from Google Collections.
Example:
String key = "hello";
Multimap<String, Integer> myMap = HashMultimap.create();
myMap.put(key, 1);
myMap.put(key, 5000);
System.out.println(myMap.get(key)); // prints either "[1, 5000]" or "[5000, 1]"
myMap = ArrayListMultimap.create();
myMap.put(key, 1);
myMap.put(key, 5000);
System.out.println(myMap.get(key)); // always prints "[1, 5000]"
Note that Multimap is not an exact equivalent of the home-baked solution; Hashtable synchronizes all its methods, while Multimap makes no such guarantee. This means that using a Multimap may cause you problems if you are using it on multiple threads. If your map is used only on one thread, it will make no difference (and you should have been using HashMap instead of Hashtable anyway).
Values of a hash table is Object so you can store a List
In a hashtable, one would use a key/value pair to store information.
In Java, the Hashtable class accepts a single value for a single key. The following is an example of an attempt to associate multiple values to a single key:
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("Answer", "42");
ht.put("Hello", "World"); // First value association for "Hello" key.
ht.put("Hello", "Mom"); // Second value association for "Hello" key.
for (Map.Entry<String, String> e : ht.entrySet()) {
System.out.println(e);
}
In an attempt to include multiple values ("World", "Mom") to a single key ("Hello"), we end up with the following result for printing the entries in the Hashtable:
Answer=42
Hello=Mom
The key/value pair of "Hello" and "World" is not in the Hashtable -- only the second "Hello" and "Mom" entry is in the Hashtable. This shows that one cannot have multiple values associate with a single key in a Hashtable.
What is really needed here is a multimap, which allows an association of multiple values to a single key.
One implementation of the multimap is Multimap from Google Collections:
Multimap<String, String> mm = HashMultimap.create();
mm.put("Answer", "42");
mm.put("Hello", "World");
mm.put("Hello", "Mom");
for (Map.Entry<String, String> e : mm.entries()) {
System.out.println(e);
}
This is similar to the example above which used Hashtable, but the behavior is quite different -- a Multimap allows the association of multiple values to a single key. The result of executing the above code is as follows:
Answer=42
Hello=Mom
Hello=World
As can be seen, for the "Hello" key, the values of "Mom" and "World" associated with it. Unlike Hashtable, it does not discard one of the values and replace it with another. The Multimap is able to hold on to multiple values for each key.
Rather than give yet another multipmap answer, I'll ask why you want to do this?
Are the multiple values related? If yes, then it's probably better that you create a data structure to hold them. If no, then perhaps it's more appropriate to use separate maps.
Are you keeping them together so that you can iterate them based on the key? You might want to look for an alternative indexing data structure, like a SkipList.
Just make your own:
Map<Object, List<Object>> multiMap = new HashMap<Object, List<Object>>();
To add:
public void add(String key, Object o) {
List<Object> list;
if (multiMap.containsKey(key)) {
list = multiMap.get(key);
list.add(o);
} else {
list = new ArrayList<Object>();
list.add(o);
multiMap.put(key, list);
}
}
As others pointed out, no. Instead, consider using a Multimap which can map many values for the same key.
The Google Collections (update: Guava) library contains one implementation, and is probably your best bet.
Edit: of course you can do as Eric suggests, and store a Collection as a value in your Hashtable (or Map, more generally), but that means writing unnecessary boilerplate code yourself. When using a library like Google Collections, it would take care of the low-level "plumbing" for you. Check out this nice example of how your code would be simplified by using Multimap instead of vanilla Java Collections classes.
None of the answers indicated what I would do first off.
The biggest jump I ever made in my OO abilities was when I decided to ALWAYS make another class when it seemed like it might be even slightly useful--and this is one of the things I've learned from following that pattern.
Nearly all the time, I find there is a relationship between the objects I'm trying to place into a hash table. More often than not, there is room for a class--even a method or two.
In fact, I often find that I don't even want a HashMap type structure--a simple HashSet does fine.
The item you are storing as the primary key can become the identity of a new object--so you might create equals and hash methods that reference only that one object (eclipse can make your equals and hash methods for you easily). that way the new object will save, sort & retrieve exactly as your original one did, then use properties to store the rest of the items.
Most of the time when I do that, I find there are a few methods that go there as well and before I know it I have a full-fledged object that should have been there all along but I never recognized, and a bunch of garbage factors out of my code.
In order to make it more of a "Baby step", I often create the new class contained in my original class--sometimes I even contain the class within a method if it makes sense to scope it that way--then I move it around as it becomes more clear that it should be a first-class class.
See the Google Collections Library for multimaps and similar such collections. The built-in collections don't have direct support for this.
What you're looking for is a Multimap. The google collections api provides a nice implementation of this and much else that's worth learning to use. Highly recommended!
Simple. Instead of
Hashtable<Key, Value>, use Hashtable<Key, Vector<Value>>.
You need to use something called a MultiMap. This is not strictly a Map however, it's a different API. It's roughly the same as a Map<K, List<V>>, but you wont have methods like entrySet() or values().
Apart from the Google Collections there is a apache Commons Collection object
for MultiMap
Following code without Google's Guava library. It is used for double value as key and sorted order
Map<Double,List<Object>> multiMap = new TreeMap<Double,List<Object>>();
for( int i= 0;i<15;i++)
{
List<Object> myClassList = multiMap.get((double)i);
if(myClassList == null)
{
myClassList = new ArrayList<Object>();
multiMap.put((double) i,myClassList);
}
myClassList.add("Value "+ i);
}
List<Object> myClassList = multiMap.get((double)0);
if(myClassList == null)
{
myClassList = new ArrayList<Object>();
multiMap.put( (double) 0,myClassList);
}
myClassList.add("Value Duplicate");
for (Map.Entry entry : multiMap.entrySet())
{
System.out.println("Key = " + entry.getKey() + ", Value = " +entry.getValue());
}