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]
Related
This question already has answers here:
How to preserve insertion order in HashMap? [duplicate]
(2 answers)
Closed 2 years ago.
I want to sort hashmap or add all keys to arraylist by creative order
For example:
HashMap<String, String> map_from_file = new HashMap<String, String>();
map_from_file.put("C", "c");
map_from_file.put("B", "b");
map_from_file.put("D", "d");
map_from_file.put("A", "a");
for (String key : map_from_file.keySet()) {
System.out.println(key);
}
Output:
A
B
C
D
I want the output to be:
C
B
D
A
Thank's for any help
Map<String, String> map_from_file = new LinkedHashMap<>();
map_from_file.put("C", "c");
map_from_file.put("B", "b");
map_from_file.put("D", "d");
map_from_file.put("A", "a");
for (String key : map_from_file.keySet()) {
System.out.println(key);
}
You must use LinkedHashMap data structure for ordered key.
This question already has answers here:
How to preserve insertion order in HashMap? [duplicate]
(2 answers)
Closed 4 years ago.
I want to generate a list of all countries in a sorted list. I tried this:
public Map<String, String> getCountryNameCodeList() {
String[] countryCodes = Locale.getISOCountries();
Arrays.sort(countryCodes);
Map<String, String> list = new HashMap<>();
for (String countryCode : countryCodes) {
Locale obj = new Locale("", countryCode);
list.put(obj.getDisplayCountry(), obj.getCountry());
}
return list;
}
But for some reason the list is unsorted. What is the proper way to fort it?
HashMap is unsorted, use LinkedHashMap:
This implementation differs from HashMap in that it maintains a
doubly-linked list running through all of its entries. This linked
list defines the iteration ordering, which is normally the order in
which keys were inserted into the map (insertion-order).
Just change
Map<String, String> list = new HashMap<>();
to:
Map<String, String> list = new LinkedHashMap<>();
This question already has answers here:
Does Java have a HashMap with reverse lookup?
(7 answers)
Closed 9 years ago.
I have a hash map and values in it. Now i want to set the values in the map as keys and keys as values. Can anyone suggest any idea?
My Map is
Map<String, String> col=new HashMap<String, String>();
col.put("one","four");
col.put("two","five");
col.put("three","Six");
Now i want to create an another map and put it in other way as i told above. ie,
Map<String, String> col2=new HashMap<String, String>();
col.put("five","one");
col.put("four","two");
col.put("Six","three");
Anybody has idea? Thanks
Like so:
Map<String, String> col2 = new HashMap<String, String>();
for (Map.Entry<String, String> e : col.entrySet()) {
col2.put(e.getValue(), e.getKey());
}
Assuming your values are unique in your hashmap, you can do like this.
// Get the value collection from the old HashMap
Collection<String> valueCollection = col.values();
Iterator<String> valueIterator = valueCollection.iterator();
HashMap<String, String> col1 = new HashMap<String, String>();
while(valueIterator.hasNext()){
String currentValue = valueIterator.next();
// Find the value in old HashMap
Iterator<String> keyIterator = col.keySet().iterator();
while(keyIterator.hasNext()){
String currentKey = keyIterator.next();
if (col.get(currentKey).equals(currentValue)){
// When found, put the value and key combination in new HashMap
col1.put(currentValue, currentKey);
break;
}
}
}
Create another Map and iterate through keys/values one by one and put in new Map. finally delete old one.
I have two hashmaps, in particular vocabs of two languages say english and german.I would like to concatenate both these map to return a single map.I tried :
hashmap.putall()
But, removed some of the entries which are common in both maps and replace it by single entry only.But i want to keep both the vocabs intact just concatenate those. Is there any method to do it? if not any other way to do. I would prefer any methods in hashmap.
[EDIT]
To make more clear, lets see two maps
at the 500 um die 500
0 1 2 0 1 2
resutls into
at the 500 um die 500
0 1 2 3 4 5
You'll have to write your own custom "putAll()` method then. Something like this would work:
HashMap<String> both = new HashMap<String>(english);
for(String key : german.keySet()) {
if(english.containsKey(key)) {
both.put(key, english.get(key)+german.get(key));
}
}
This first copies the English HashMap. Then puts in all the German words, concatenating if there is a duplicate key. You might want some kind of separator character like a / in between so you can later extract the two.
There isn't anything like that in the Java main library itself, you will have to use something provided by third parties like Google Guava's Multimap, it does exactly what you want, or build something like this manually.
You can download the Guava library at the project's website. Using a multimap is the same as using a map, as in:
Multimap<String,String> both = new ArrayListMultimap <String,String>();
both.putAll( german );
both.putAll( english);
for ( Entry<String,String> entry : both.entrySet() ) {
System.out.printf( "%s -> %s%n", entry.getKey(), entry.getValue() );
}
This code will print all key-value pairs including the ones that are present on both maps. So, if you have me->me at both german and english they would be printed twice.
You cannot do that directly with any Map implementation, since in a map, each key is unique.
A possible workaround is to use Map<Key, List<Value>>, and then do the concatenation of your maps manually. The advantage of using a List for the concatenated map, is that it will be easy to retrieve each of the individual values without any extra fiddling.
Something like that would work:
public Map<Key, List<Value>> concat(Map<Key, Value> first, Map<Key, Value> second){
Map<Key, List<Value>> concat = new HashMap<Key, List<Value>>();
putMulti(first, concat);
putMulti(second, concat);
return concat;
}
private void putMulti(Map<Key, Value> content, Map<Key, List<Value>> dest){
for(Map.Entry<Key, Value> entry : content){
List<Value> vals = dest.get(entry.getKey());
if(vals == null){
vals = new ArrayList<Value>();
dest.put(entry.getKey(), vals);
}
vals.add(entry.getValue());
}
}
Similar to #tskuzzy's answer
Map<String, String> both = new HashMap<String, String>();
both.putAll(german);
both.putAll(english);
for (String e : english.keySet())
if (german.containsKey(e))
both.put(e, english.get(e) + german.get(e));
Slight improvisation of #tskuzzy and #Peter's answer here. Just define your own StrangeHashMap by extending HashMap.
public class StrangeHashMap extends HashMap<String, String> {
#Override
public String put(String key, String value) {
if(this.containsKey(key)) {
return super.put(key, super.get(key) + value);
} else {
return super.put(key, value);
}
}
}
You can use it as so:
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "Value1");
map1.put("key2", "Value2");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("key1", "Value2");
map2.put("key3", "Value3");
Map<String, String> all = new StrangeHashMap();
all.putAll(map1);
all.putAll(map2);
System.out.println(all);
The above prints the below for me:
{key3=Value3, key2=Value2, key1=Value1Value2}
Given the new elements in the question, it seems that what you actually need to use is lists. In this case, you can just do:
List<String> english = ...;
List<String> german = ...;
List<String> concat = new ArrayList<String>(english.size() + german.size());
concat.addAll(english);
concat.addAll(german);
And there you are. You can still use concat.get(n) to retreive the value nth value in the concatenated list.
This question already has answers here:
Closed 11 years ago.
Got the solution.. Used linkedHashMap and was able to store the sorted key values in an array. Here's the link for the code.
Possible Duplicate:
store key values of sorted hashmap in string[]
I created a hashmap and then 'sorted by value' the elements in the map using this code.
The code worked and i was able to display on screen the key value pairs sorted by value.
Now I want to store the keys(from the sorted elements) in a String[]. HashMap.keySet().toArray() doesn't help as the entired HashMap are not sorted.
Can anyone please suggest a method to do this?
further clarifying the situation - Suppose I have key value pairs like (a,1)(b,23)(c,7)
by using the above link, i was able to get (a,1)(c,7)(b,23) as output. I want to store {a,c,b} as a string array.
I hope the problem is clear now.
Reusing this code you would just use
List keys = sortByValue(m);
String[] keyArray = keys.toArray(new String[keys.size()]);
Using generics would make this nicer. I would also sort by Map.Entry (from entrySet()) which would be faster and simpler.
Sorting my keys is simple, use TreeMap.
TreepMap sortedMap = new TreeMap(someHashMap);
String[] sortedKeys = sortedMap.keySet().toArray();
That code is not really sorting the HashMap - it is merely returning the keys, sorted by their value:
So all you need is:
Object[] key_array = sortByValue(m).toArray();
I'd go either for something like
private static String[] keysSortedByValue(final Map<String, String> m) {
final String[] result = m.keySet().toArray(new String[m.size()]);
Arrays.sort(result, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
final String v1 = m.get(o1);
final String v2 = m.get(o2);
if (v1==v2) return 0;
if (v1==null) return -1;
if (v2==null) return +1;
return v1.compareTo(v2);
}
});
return result;
}
or use Map.Entry[] for greater efficiency (avoiding the lookup).
I would use Google Collection:
Map<String, String> map = new HashMap<String, String>( );
map.put("ABC1", "VALUE1");
map.put("ABC7", "VALUE1");
map.put("ABC2", "VALUE2");
map.put("ABC3", "VALUE1");
Multimap multimap = TreeMultimap.create();
for(Map.Entry<String, String> entry: map.entrySet() ) {
multimap.put( entry.getValue(), entry.getKey() );
}
System.out.println( Arrays.toString( multimap.values().toArray() ));