I want to get the first value from my HashMap while I do not know the key for the value.
Is it possible? Are there are libraries to do this?
You could use a java.util.LinkedHashMap<K, V>. Then you can iterate through the map in insertion order.
To only get the first entry you can use an iterator:
Map<String, String > map = new LinkedHashMap<String, String >();
// ... fill the map
Entry<String, String > next = map.entrySet().iterator().next();
next.getKey();
next.getValue();
If you want the first key that you inserted into the map, then use LinkedHashMap. It's basically a HashMap that remembers the order in which things were inserted, so you can iterate them in the original order.
If you want to select the first key in the natural ordering of the key class; or if you want to select the first key under some ordering of your own, then use TreeMap. It's a type of map that sorts things as you insert them into the map. You can set up a TreeMap with its own Comparator, if you want to specify the order in which the keys are sorted. If you don't supply a Comparator when you create a TreeMap, then it will sort the keys by their natural order.
I recommend reading the Javadocs for both TreeMap and LinkedHashMap before you decide which of the two is appropriate for your application.
Use a LinkedHashMap or TreeMap to maintain insertion order in the first place, after that it is just a matter of using the Iterator.
You can do something like this.
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
//This will be your very first element
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
Related
I have a sorted map and would like to retrieve the values in the order of their corresponding keys. I.e. if my sorted map has (1,6), (2,4), (3,1), I want to retrieve [6,4,1].
Is there something faster than iterating over the sorted map like so?
SortedMap<Double, Double> sortedMap = new TreeMap<Double, Double>(sortedMap.size());
List<Double> values = new ArrayList<Double>();
for (Entry<Double, Double> entry : sortedMap.entrySet()) {
values.add(entry.getValue());
}
I don't think simply doing:
values = new ArrayList<Double>(sortedMap.values())
would work since sortedMap.values() returns a Collection with no guarantees on the order but iterating over the map doesn't strike me as efficient.
sortedMap.values() returns a Collection with no guarantees on the order
According to docs for SortedMap the order is guaranteed, see:
http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html#values()
Why do you think iterating over a sorted map is slow? In order to retrieve all the values you would have to eventually iterate through the entire Map. So the time complexity will always be O(n).
I have the following entries in my HashMap
<key1,value1>
<key2,value2>
<key3,value2>
<key4,value4>
<key5,value2>
I would like to find all the Keys that contain the value "value2".
The answer would be a KeySet containing the following keys:
{key2,key3,key4}
Is it possible to accomplish that in a HashMap?
thanks
just Iterate entries of your map and check if the value of the current entry is equal to "value2" then add it to Set.
try this
Set<String> keySet = new HashSet<String>();
for (Map.Entry<String, String> entry : map.entrySet())
{
if(entry.getValue().equals("value2")
{
keySet.add(entry.getKey());
}
}
I guess there is no other option since you have duplicate values in your map.
I would like to find all the Keys that contain the value "value2". The answer would be a KeySet containing the following keys: {key2,key3,key4}
Two options:
new map where the values are the keys and the keys are the values (if every key and value are unique)
iterate through the entries of your map and check if the value of the current entry is equal to "value2", if yes add it a set with the results
Map is supposed to use in such way that access the values using the keys, but it seems you are doing it in reverse.
If you are sure about what you are doing, there is no good way to accomplish. Iterate over map and store the keys in separate list.
More over Look at Gauva's Multimap, that might suits for your requirment.
I research a position of my key in hashMap.
Example :
HashMap<Integer, String> ht = new HashMap();
ht.put(1, "c");
ht.put(10, "b");
ht.put(8, "r");
System.out.println(ht);
10 has position 3 in HashMap, 8 has position 2 ...
So I have two questions :
how to retreive these positions from HashMap?
When i have a much element, i use hashMap to retreive a positions or Binary Search ?
HashMap is not a sorted or ordered Map implementation, so there isn't a "position" here.
LinkedHashMap is an ordered one, TreeMap is a sorted one.
A hash map is not ordered, so there are no real concepts of positions in a hashmap. If you need an ordered/sorted map, have a look at TreeMap or LinkedHashMap.
I using a Guava MultiMap (impl LinkedListMultimap) to allow me to store multiple values for a key, but then I want to sort the map by the highest value and return the keys.
i.e
After first run I have
key1:{13}
key2:{7}
key3:{11}
After second run I now have
key1:{13,14}
key2:{7,18}
key3:{11,1}
After third run I now have
key1:{13,14,16}
key2:{7,18,6}
key3:{11,1,22}
I want an order of
key3
key2
key1
and I want to output the keys (I dont need to know the values any longer)
I cant work out a way to do that, I dont have to use MultiMap it just looked like it might help
If I were you, I'd start by not using a Multimap, but rather, using a Map to track the greatest value associated with each key. Then, you have a Map<String, Integer>, and if you don't need to save the Map afterwards, then I'd do something like
final Map<String, Integer> map = ...
return Ordering.natural().onResultOf(Functions.forMap(map)).reverse()
// a comparator to compare strings in descending order of their
// associated values
.immutableSortedCopy(map.keySet());
To unpack a bit:
Ordering.natural() // the natural ordering on integers
.onResultOf(
Functions.forMap(map) // use the Map<String, Integer> as a Function
// this ordering now compares Strings by the natural ordering of
// the integers they're mapped to
.reverse(); // reverses the ordering, so it now sorts in descending order
What I would do is stick the entrySet into a TreeSet with a custom comparator. Then pull out the keys.
sortedEntries = Sets.newTreeSet(comparator).addAll(multimap.entries());
return Collections2.transform(sortedEntries, keyExtractor);
The implementation of keyExtractor, comparator and parametrization is left as an exercise to the reader.
I am using String object as the key to a linkedhashmap.
How can I get all the entries in the LinkedHashMap?
You have three options that depend on whether you need just keys, just values or both
Set<String> keys = yourMap.keySet();
Collection<YourValueClass> values = yourMap.values();
Set<Map.Entry<String,YourValueClass>> pairs = yourMap.entrySet();
then you can easily iterate over them if you need. Actually all of them allow iterating using a simple foreach loop:
for (Map.Entry<String,YourClassValue> e : yourMap.entrySet())
// do something
You can use the entrySet method, which returns a set containing the key-value pairs in your map.