Hash map with multiple keys? [duplicate] - java

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

Related

Strings as key in Hashmap [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I'm newbie with Java
Is it possible to convert a String, or a String[] as the keys of an Hashmap?
I mean:
String keysToConvert = "key1,key2,key3";
into
HashMap<String, Double> hashmap = new HashMap<String, Double>();
[apply in some way the keys of the string]
hashmap.get("key2");
I know that hashmap.get("key2");has no value in this moment. I just would know if there is a way to load the keys in an HashMap.
hashmap.put("key2", 1.0d);
System.out.println(hashmap.get("key2")); // prints 1.0
This is the basic usage of a Map
If you have String[], you can add them using a for-each loop:
String[] keys = {"key1", "key2", "key3"};
HashMap<String, Double> hashmap = new HashMap<String, Double>();
for (String key : keys) {
hashmap.put(key, null);
}

Java: Find matching keys of two HashMaps [duplicate]

This question already has answers here:
Intersection of java.util.Map
(6 answers)
Closed 8 years ago.
I have two HashMaps, say HashMapA and HashMapB. What would be an efficient way of finding keys that exists in both HashMaps? My current implementation looks like this:
Integer key;
/* create iterator */
Iterator<Map.Entry<Integer, Foo>> it = HashMapA.entrySet().iterator;
/* iterate through HashMapA using iterator*/
while (it.hasNext()) {
key = it.next().getKey();
if (HashMapB.containsKey(key)) {
/* matching key found */
System.out.println("Got one: " + key);
}
}
This appears to work, but looks quiet inefficient. Is there something like
Integer keyInBothMaps = HashMapA.containsKeyOf(HashMapB);
?
You are looking at the keys of the map so start with the keySet();
You can then look at the Set interface and see the method retainAll
http://docs.oracle.com/javase/8/docs/api/java/util/Set.html#retainAll-java.util.Collection-
This gives you:
map1.keySet().retainAll(map2.keySet())
However that will modify the map so you should copy the set:
new HashSet<>(map1.keySet()).retainAll(map2.keySet())
You can use Set.retainAll.
Here's an ugly example:
Map<String, String> m0 = new HashMap<String, String>();
m0.put("a", "a");
m0.put("b", "b");
Map<String, String> m1 = new HashMap<String, String>();
m1.put("c", "c");
m1.put("b", "b");
Set<String> s = new HashSet<String>(m0.keySet());
s.retainAll(m1.keySet());
System.out.println(s);
Output
[b]

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

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

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.

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