How can we compare two hashmap's in java [duplicate] - java

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);
}

Related

How is the sequence decided when looping through map [duplicate]

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.

Hash map with multiple keys? [duplicate]

This question already has answers here:
How to create a HashMap with two keys (Key-Pair, Value)?
(14 answers)
Closed 6 years ago.
Can I have a hash map in Java that looks like this?
HashMap<String, String, Integer> hmap = new HashMap<String, String, Integer>()
My question is similar to this one hereQuestion
I'm a newbie to Java. So what I want to know is, what would be the best data structure to use if I need something like above, if that is not valid?
Create a simple class holding two String objects:
public class MyKey {
private String a;
private String b;
// ... accessors, mutators etc.
}
And then use it's objects as keys in your map:
HashMap<MyKey, Integer> hmap = new HashMap<>()
Later, to add a new entry:
hmap.put(new MyKey("a", "b"), 2);

How can you sort values in HashMap [duplicate]

This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 9 years ago.
For example you have a HashMap<String, String>
how can you sort values in the hashmap and print them to console
what would be the best ways to do it?
This should do it:
Map<String, String> asso = new HashMap<String, String>
// add some tuples to asso
List<String> values = new ArrayList(asso.values());
Collections.sort(values); // assumes an appropriate comparator implementation for the value type
There isn't a way to retrieve a HashMap tuple by value sorted order afaik.

Getting first the first thing in HashMap? [duplicate]

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());
}

how to sort hashmap by values? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
I need to sort my hashmap according to the values stored in it. The hashmap contains the contacts name stored in phone.also I need that the keys get automatically sorted as soon as I sort the values.or you can say the keys and values are bounded together thus any changes in values should get reflected in keys.
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,froyo);
map.put(2,abby);
map.put(3,denver);
map.put(4,frost);
map.put(5,daisy);
required output:
2,abby;
5,daisy;
3,denver;
4,frost;
1,froyo;
private static class MyMapComparator implements Comparator<Map.Entry<Integer, String>>
{
#Override
public int compare(Map.Entry<Integer, String> a, Map.Entry<Integer, String> b) {
return a.getValue().compareTo(b.getValue());
}
}
...
List<Map.Entry<Integer, String>> entries = new ArrayList<Map.Entry<Integer, String>>(map.entries());
Collections.sort(entries, new MyMapComparator());

Categories

Resources