I created a hashmap as shown below:
Map<String, String> streetno = new HashMap<String, String>();
streetno.put("3", "Sachin");
streetno.put("2", "Dravid");
streetno.put("1", "Sehwag");
streetno.put("5", "Laxman");
streetno.put("4", "Kohli");
Now I want to create a new hashmap where key of the above hashmap becomes value and value becomes key as shown below:
Map<String, String> streetname = new HashMap<String, String>();
streetname.put("Sachin", "3");
streetname.put("Dravid", "2");
streetname.put("Sehwag", "1");
streetname.put("Laxman", "5");
streetname.put("Kohli", "4");
I don't know how to do that.. Can anyone help me out with this..
Map<String, String> streetname = new HashMap<String, String>();
for (Entry<String,String> e : streetno.entrySet()) {
streetname.put(e.getValue(), e.getKey());
}
Here, the for loop iterates over all entries (i.e. key/value pairs) in the original map, and inserts them into the second map with the key and value swapped over.
It is probably a good idea to check that put() returns null. If you get a non-null value, this means that the values in streetno are not unique. Since this is homework, I leave it to you to figure out the consequences, and how best to handle this.
Perfect you are almost there. Now you need to iterate the first hash map keys and simulate what you have done in those 5 lines:
streetname.put("Sachin", "3");
streetname.put("Dravid", "2");
streetname.put("Sehwag", "1");
streetname.put("Laxman", "5");
streetname.put("Kohli", "4");
Tip: iteration over map might be a bit tricky for you, but usually it is done like that:
for (String key : streetno.keySet()) {
...
}
Good luck with your homework!
Java 8:
Map<String, String> streetname =
streetno.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
Note:
If you are tempted to use parellelstream() instead of stream() think twice about it. This would only be appropriate if your Map is extremely large.
Related
When i try to add hashMap to another HashMap i lose old varaible. How can i fix this problem? My code is something like that.
HashMap<String, String> tmp = new HashMap<String, String>();
HashMap<String, String> map = new HashMap<String, String>();
tmp = ((HashMap<String, String>)intent.getSerializableExtra("map"));
map.putAll(tmp);
when i use this code map elements always equals tmp elements. It is not stored old elements.
Thanks for help.
HashMap<String, String> map = new HashMap<String, String>(); creates a new, empty, HashMap instance. Therefore after a call to map.putAll(tmp), your map would only contain the entries of tmp.
If map has previous entries, you shouldn't assign a new instance to this variable.
That said, even if map had previous entries, putting the entries of tmp in it would overwrite the values of all the keys that exist in both map and tmp.
Once you have updated map to not be re-initialized every time, you can avoid overwriting any existing key-value pairs in map by looping as follows:
for (String key : tmp.keySet()) {
if (!map.containsKey(key)) {
map.put(key, tmp.get(key);
}
}
I'm not sure from your question if this is exactly what you are asking, but it may be useful. Eran's suggestion (using HashMap<String, List<String>>) is also a good one if you want to store multiple Strings per key.
I am trying to combine two different hashmaps. But in those two maps, there are some duplicate entries, so I have to remove thoese entries after combine.
For example:
HashMap 1:
100 hello
101 nice
HashMap 2:
100 hello
102 good
After combine, the hashmap should looks like:
100 hello
101 nice
102 good
I have tried putall,but seems it does not remove duplicate entries.
Could someone help me on a fast way to do that?
I don't see a problem in your approach.
HashMap<String, Object> first = new HashMap<String, Object>();
HashMap<String, Object> second = new HashMap<String, Object>();
first.put("100", "hello");
first.put("101", "nice");
second.put("100", "hello");
second.put("102", "good");
first.putAll(second);
System.out.println(first);
outputs
{102=good, 101=nice, 100=hello}
Try to check, if your handling of HashMaps is correct.
The keys of a HashMap can't be duplicates, because they are represented in a Set, so merging the two maps should do the work.
you can add two hashmap map1 and map2 to third hashmap map3 just declare the input type for value as Object as all the data type have their super class as Object class.
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, String> map2 = new HashMap<String, String>();
HashMap<String, Object> map3;
map3 = new HashMap<>();
map3.putAll(map1);
map3.putAll(map2);
I search map implementation with multiple key. I know Apache Commons but it dosen't satisfy me.
I want to be able to pass one key and get all entries which contain the passed key, e.g.
MultiKeyMap mkm = new MultiKeyMap();
mkm.put("key1", "key2", "key3", "1");
mkm.put("key1", "key22", "key33", "2");
mkm.put("key12", "key22", "key32", "3");
mkm.get("key1");
returns null but in this case I want to get "1" and "2"
My own implementation is not an option. I want to use something which I can trust.
I think Guava has a Table implementation Table<Key1,Key2,Value> where you can do table.get(key1) or table.get(key2) or table.get(key1, key2). I think it only supports two keys per table, but not sure. Might want to take a look at that.
Guava Table javadoc
I think you can do this with HashMap
HashMap<String, ArrayList<String>> map = new HashMap<>();
ArrayList<String> ls=new ArrayList<>();
ArrayList<String> ls2=new ArrayList<>();
ls.add("key3");
ls.add("1");
ls.add("key2");
ls.add("key22");
ls.add("key33");
ls.add("2");
ls2.add("key22");
ls2.add("key32");
ls2.add("3");
map.put("key1",ls);
map.put("key12", ls2);
map.get("key1");
If you can turn the requirement around and put the value multiple times, once for each key, then Guava's MultiMap is very nice to use:
Multimap<String, String> map = HashMultimap.create();
map.put("key1", "1");
map.put("key2", "1");
map.put("key3", "1");
map.put("key1", "2");
map.put("key22", "2");
map.put("key33", "2");
map.put("key12", "3");
map.put("key22", "3");
map.put("key32", "3");
Collection<String> values = map.get("key1");
System.out.println(values);
prints
[2, 1]
I've set a HashMap on certain order but it is iterated on a strange order!
Please consider code below:
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", "1");
map.put("Name", "the name");
map.put("Sort", "the sort");
map.put("Type", "the type");
...
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
and the result:
Name: the name
Sort: the sort
Type: the type
ID: 1
I need to iterate it in order i've put the entries.
Any help will be appreciated.
That's how HashMap works internally. Replace HashMap with LinkedHashMap which additionally remembers the order of insertion:
Map<String, String> map = new LinkedHashMap<String, String>();
The order depends on the result of the hashCode() function in the keys you are inserting which, unless you did something strange, is going to be mostly random (but consistent). What you are looking for is a sorted map such as a LinkedHashMap
Check out a little bit about how hashtables work here if you are interested in the details.
I have a map code in java.This is my following code.
Map<String, String> map = new HashMap<String, String>();
map.put("type", "One");
map.put("name", "Two");
map.put("setup", "Three");
System.out.println("Map Values Before: ");
Set<String> keys = map.keySet();
for (Iterator<String> i = keys.iterator(); i.hasNext();) {
String key = (String) i.next();
String value = (String) map.get(key);
Map<String, String> map = new HashMap<String, String>();
}
Here i am able to get the output.My problem is i need match each key values to separate strings for further use in my code.How to i can get each key value in separate strings.Please help me.
This ill allow you to iterate through your maps keyset. However, depending on what you need Guava has a bi-directional map implementation which could be useful in your case.
for(String key:map.keySet())
System.out.println("key: "+key+" value: "+map.get(key));
Taking a guess at your meaning, you want to populate variables corresponding to the keys
String type; // gets the value "One"
String name; // gets the value "Two"
String name; // gets the value "Three"
Now I assume that simple code such as
type = map.get("type");
is unacceptable, or you surely would not ask the question, so you want some programmatic way of iterating the set of properties?
In which case look at the Reflection APIs.
Please confirm that this is the problem you're trying to solve, and have a look at the APIs, if you then have specific questions follow up ...