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.
Related
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.
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:
How to compare two hashmaps in java?
(4 answers)
Closed 9 years ago.
My application storing the values from database and user values and compare them. In order to store those values I have used hashmap with key as integer and list as data and store the values. It is not necessary that the key values and data should be same but all the data values in 2 hashmaps should be same
The hashmaps are like this:
key : value
1-[cd,done]
2-[mb,done]
3-[core,done]
other one is
1-[mb,done]
2-[core,done]
3-[cd,done]
In code the above hasmap should be equal irrespective of what order the values are stored
but as of now I am not able to code it correctly...
As I understand, you just want to test that the values of the maps are equals not the maps themself.
Thus you can just compare the values() using the containsAll method:
hashMap1.values().containsAll(hashMap2.values()) &&
hashMap2.values().containsAll(hashMap1.values());
You could also use the CollectionUtils.isEqualCollection to simplify the code:
CollectionUtils.isEqualCollection(hashMap1.values(), hashMap2.values());
public static void main(String[] args) {
Map<Integer,String> map1 = new HashMap<Integer,String>();
Map<Integer,String> map2 = new HashMap<Integer,String>();
map1.put(1, "ABC");
map1.put(2, "1123");
map2.put(1, "XYZ");
boolean val = map1.keySet().containsAll(map2.keySet());
for (Entry<Integer, String> str : map1.entrySet()) {
System.out.println("================="+str.getKey());
if(map2.containsKey(str.getKey())){
System.out.println("Map2 Contains Map 1 Key");
}
}
System.out.println("================="+val);
}
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());
}