This question already has answers here:
is the Java HashMap keySet() iteration order consistent?
(12 answers)
Closed 2 years ago.
I have a question about the sequence of hash map. For example, in the following code:
public class MapEntrySetOrder {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
String[] l = new String[]{"Entry", "Set", "HashMap", "Order"};
for (String s : l) {
map.putIfAbsent(s, s);
}
for(Map.Entry<String, String> e : map.entrySet()) {
System.out.println("key:" + e.getKey());
}
}
}
I know there is no order maintained in hashmap, but every time I print the keys thru a loop, there are all in same order, and the order is not from the beginning of the original list nor from the end of the original list:
key:Order
key:Entry
key:Set
key:HashMap
So how is the order decided. If it is in a random way, why every time I print they are the same result?
Use HashMap for fast non-ordered Map
Use LinkedHashMap for order of adding to the Map
Use TreeMap for any order you wish (with Comparator implementation)
Also I think you have same order each time because you use map.entrySet() instead of map.keySet()
Hashmap does not guarantee any order.
If you want ordered sequence use LinkedHashMap instead.
Related
This question already has answers here:
How do I efficiently iterate over each entry in a Java Map?
(46 answers)
Closed 5 years ago.
How do I search for a Hashmap that contains String as a key and list of objects as value?
HashMap<String,List<PageObjectBaseClass>> ObjList1;
When I used
for (HashMap<String,List<PageObjectBaseClass>> map : ObjList1)
Am getting the error "Can only iterate over an array or an instance of java.lang.Iterable"
You'll need to enumerate over the entrySet like this:
for (Map.Entry<String, List<PageObjectBaseClass>> map : ObjList1.entrySet()){
....
}
There are many ways. The one I find most idiomatic and expressive is Map.forEach:
yourMap.forEach((key, value) -> {
// key is of type String
// value is List<PageObjectBaseClass>
});
You can only use the extended for-loop over objects that implement the Iterable interface. Map does not.
However it provides some utility method to access collections of its entries, keys and values which are of type Iterable. Therefore consider the following examples:
HashMap<A, B> map = new HashMap<>();
// Entries
for (Map.Entry<A, B> entry : map.entrySet​()) { ... }
// Keys
for (A key : map.keySet()) { ... }
// Values
for (B value : map.values()) { ... }
Here are links to the documentation of all three methods:
Map#entrySet - documentation
Map#keySet - documentation
Map#values - documentation
Note that all three accesses are fast, O(1). As you get collections that are internally used by the map. That is also why they are backed by the map, which means if you change something on the collections or the entries, the changes will be reflected inside the map too.
This an example from here
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
This question already has answers here:
Sorting hashmap based on keys
(9 answers)
Closed 3 years ago.
I want to sort the following hashmap by value. Hashmap is Hashmap<String, Arraylist<String>> and the data in it is as following:
924911637601767=[1, John]
864467483673342=[2, Paul]
825398867568656=[8, James]
1034643283235161=[5,Elina]
I want to sort the above data with respect to the counter values i.e 1,2,8,5
After Sorting
924911637601767=[1, John]
864467483673342=[2, Paul]
1034643283235161=[5,Elina]
825398867568656=[8, James]
HashMap no guarantees as to the order.
If you want get list by order like you want, you should sort list values of the HashMap.
Example can be found here How to sort a HashMap in Java
This class makes no guarantees as to the order of the map; in particular, it >does not guarantee that the order will remain constant over time.
See http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
In other words, what you are looking for cannot be achieved as you want.
However, what you can do is to transform your Hashmap to a list of objects that consist of each map entry elements.
Object: key, name, number for example.
Your object can then implement java.lang.Comparable in order to sort it as you want.
See https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
The hashmap abstract data type is inherently unsorted. Depending on your use case, you could do something like:
import java.util.*;
class Test {
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
map.put("924911637601767", Arrays.asList("1", "John"));
map.put("864467483673342", Arrays.asList("2", "Paul"));
map.put("825398867568656", Arrays.asList("8", "James"));
map.put("1034643283235161", Arrays.asList("5", "Elina"));
List<Map.Entry<String,List<String>>> entries = new ArrayList<Map.Entry<String,List<String>>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String,List<String>>>() {
public int compare(Map.Entry<String,List<String>> l1, Map.Entry<String,List<String>> l2) {
return l1.getValue().get(0).compareTo(l2.getValue().get(0));
}
});
for (Map.Entry<String,List<String>> e : entries) {
System.out.println(e.getKey() + " : [" + e.getValue().get(0)
+ ", " + e.getValue().get(1) + "]");
}
}
}
Use the sortedMap Interface if you are interested in sorted order and also want to keep a map.
TreeMap could be a choice.
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
This question already has answers here:
Difference between HashMap, LinkedHashMap and TreeMap
(17 answers)
Closed 7 years ago.
I want to know if my HashMap collection will be always on the same order
Map<Integer, Long> map = new HashMap<Integer, Long>(0);
for(Integer key : users) {
map.put( key , (long) 0 );
}
for( ... ){
...
if( ... ) ){
map.put( t.get(key) , map.get(key) + 1);
}
}
I send this collection to javascript with ajax
$.each( jsonData[i].totalMap , function(key, value) {
rows.push(value);
});
will have always the same order of the element of the Map as i put them in my controller ?
If you use a LinkedHashMap, the order will be kept (i.e., by default, the keys will always be iterated in the same order they were inserted into the Map).
If the keys and values are always the same, the map size is the same, and the HashMap is initialized in the same way, then yes. However for guaranteed iteration order, use a LinkedHashMap.
This question already has answers here:
Java Class that implements Map and keeps insertion order?
(8 answers)
Closed 9 years ago.
So i've created an hashmap, but i need to get the first key that i entered.
This is the code i'm using:
First:
public static Map<String, Inventory> banks = new HashMap<String, Inventory>();
Second:
for(int i = 0; i < banks.size(); i++) {
InventoryManager.saveToYaml(banks.get(i), size, //GET HERE);
}
Where it says //GET HERE i want to get the String from the hasmap.
Thanks for help.
HashMap does not manatain the order of insertion of keys.
LinkedHashMap should be used as it provides predictable iteration order which is normally the order in which keys were inserted into the map (insertion-order).
You can use the MapEntry method to iterate over your the LinkedHashMap. So here is what you need to do in your code. First change your banks map from HashMap to the LinkedHashMap:
public static Map<String, Inventory> banks = new LinkedHashMap<String, Inventory>();
And then simply iterate it like this:
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
If you just need the first element of the LinkedHashMap then you can do this:
banks.entrySet().iterator().next();
Answering the question in the title: to get the first key that was inserted, do this:
public static Map<String, Inventory> banks
= new LinkedHashMap<String, Inventory>();
String firstKey = banks.keySet().iterator().next();
Notice that you must use a LinkedHashMap to preserve the same insertion order when iterating over a map. To iterate over each of the keys in order, starting with the first, do this (and I believe this is what you intended):
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
This question already has answers here:
Partial search in HashMap
(5 answers)
Closed 6 years ago.
I am currently using HashMap<String, Integer> which is filled with keys of type String which are all, let's say, 5 chars long. How can I search for an specific key of 4 chars or less, which is part and at the beginning of some other keys and get all hits as a collection of <Key, Value>?
Iterate is your only option unless you create a custom data structure:
for (Entry<String, Integer> e : map.entrySet()) {
if (e.getKey().startsWith("xxxx")) {
//add to my result list
}
}
If you need something more time efficient then you'd need an implementation of map where you are tracking these partial keys.
It seems like a use case for TreeMap rather than HashMap. The difference is that TreeMap preserves order. So you can find your partial match much quicker. You don't have to go through the whole map.
Check this question Partial search in HashMap
You cannot do this via HashMap, you should write your own implementation for Map for implementing string length based searching in a map.
Map<String, Integer> result = new HashMap<String, Integer>;
for(String key : yourMap.keySet()) {
if(key.length() == 4){
result.put(key, yourMap.get(key);
}
}
After executing this code you have all key/value pairs with 4 letter keys in result.
Set<Entry<String, Integer>> s1 = map.entrySet();
for (Entry<String, Integer> entry : s1) {
if(entry.getKey().length == 4)
//add it to a map;
}
First get the entry set to your hashmap. Iterate through the set and check the length of each key and add it to a map or use it as u want it.
With HashMap<String, Integer> you can only go through keySet() and do contains() for String keys and your pattern.
As has been noted, there isn't a terribly efficient* way to do it with the datastructure you have specified. However, if you add an additional Map<Integer, List<String>> to keep track of the mapping from string length to the list of all keys with that length, then you will be able to do this very efficiently.
*Using just the Map<String, Integer>, you would need to iterate through the entire capacity of the larger map, whereas adding this supplemental datastructure would impose an O(1) lookup (assuming you used a HashMap) followed by iteration through just the result set, which is the fastest possible outcome.
You can try this approach:
public Map<String,Integer> filterMap(Map<String, Integer> inputMap){
Map<String, Integer> resultHashMap = new HashMap<String, Integer>();
for (String key : inputMap.keySet()) {
if(key.length()==5){
resultHashMap.put(key,inputMap.get(key));
}
}
return resultHashMap;
}