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.
Related
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.
I have a HashMap like below:
map.put("1","One"); \\KV1
map.put("3","Three"); \\KV2
map.put("2","Two"); \\KV3
map.put("5","Five"); \\KV4
map.put("4","Four"); \\KV5
Is there any function where I can get top 3(KV1,KV2,KV3) or bottom 3(KV3,KV4,KV5) key-value pairs? or may be any function by which I can delete top n or bottom n elements?
Thanks in advance.
You can remove n elements from a map without iteration this way
map.keySet().removeAll(Arrays.asList(map.keySet().toArray()).subList(0, 5));
There are some terrible answers to this question.
Firstly, it depends what you mean by top. Insertion order or natural sorted order?
A LinkedHashMap preserves insertion order. A TreeMap maintains its keys in natural sorted order.
If it's a sorted map, then you can request a view of the keys using Treemap.headMap(K key), tailMap() and subMap();
If it's insertion order then you'll have to extract the submap yourself. Guava provides a helper in Maps called Maps.filterKeys that will allow you to view the underlying map fltered by a Predicate you pass in. This is useful if you don't want to copy the map, just view it differently. Of course, you can always copy the resultant map if that's what you want or roll your own more specialised case.
This question shows how to write a generic subMap method for LinkedHashMaps.
LinkedHashMap maintains a linked list of the entries in the map, in the order in which they were inserted.
Map<String,String> map = new LinkedHashMap<String, String>();
map.put("1","One"); //KV1
map.put("3","Three"); //KV2
map.put("2","Two"); //KV3
map.put("5","Five"); //KV4
map.put("4","Four"); //KV5
for(Map.Entry<String, String> mapentry : map.entrySet() ){
System.out.println(mapentry.getKey()); // you can get the keys and values
System.out.println(mapentry.getValue());
}
Maybe this can work for skipping n elements at the end of list, limit here is (n-m) where m is the number of elements to be skipped at the bottom of the list
items.entrySet().stream()
.limit(limit)
.collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll );
Or you can use skip to ignore elements at the start of the map, where skipElements here is the number of elements that you want to skip in the beginning of the list,
items.entrySet().stream()
.skip(skipElements)
.collect(LinkedHashMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll );
I haven't tested this.
Use a SortedMap, such as a TreeMap instead of a HashMap. You can then iterate through the keys in order. That makes it possible to find and delete the 3 smallest keys. Delete the three largest key by finding and then deleting the last key three times.
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());
}
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.