I have a HashMap "stateCityMap" which is a Map>. the Keys are the States ie Goa,Kerala etc and the Values are the Cities ie Panjim,Margao etc. I want to Check if a particular city is present in the HashMap, eg.Margao and give the corresponding key of that value as the result..but everytime i ran the below code.it performs the else part(when the city is not present in the HashMAp).
city :- is the name of the city I pass to this function
Code:
public String getState(Map<String, List<String>> stateCityMap, String city) throws CityNotFoundException {
HashMap<String, List<String>> g = new HashMap<String, List<String>>(stateCityMap);
if(g.containsValue(city)){
System.out.println("State:- " +g.get(city));
}
else {
throw new CityNotFoundException("City Not Found");
}
return null;
}
Why is it doing that? why am I getting the wrong result?
It's not efficient, but you need to scan through each list in the map:
public String getState(Map<String, List<String>> stateCityMap, String city) throws CityNotFoundException {
for (Map.Entry<String, List<String>> entry : stateCityMap.entrySet()) {
if (entry.getValue().contains(city)) {
return entry.getKey();
}
}
throw new CityNotFoundException("City Not Found");
}
containsValue method returns true if the map maps one or more keys to the specified value.
In your case type of value is List, but you are calling containsValue method by passing String. So it will always returns false.
Since your value type is List, you will end up iterating all keys and all values to find if a city exists in any of the lists.
Better is to maintain two maps. Challenge will be to make sure that both maps always get updated (insert, delete, update) correctly.
Hope that helps.
Related
I have two string value ID and Value coming from my code, I need to store this in a map without iterating over the map but by checking by the key value if it exists in the map.
The ID can come many times with different value and in that case I have add it to the already existing entry of the ID and add the value along with the existing value
I created a Map with String and List to add the values but I am facing difficulties,
Map < String, List< String >> accessMap = new HashMap < String, List< String>>();
If the key is not present, add a new entry with ID and Value (as List).
How to find the key in the map and get the entrySet without iterating over the map and add the value alone, if the ID is already present in the map.
Example,
while(accessList.hasNext()){
....
....
String id = accessEntry.get(ID);
String value = accessEntry.get(Value);
/*Add the id and value to the map if not present, if ID is present add the *value alone to the entrySet.Value (which is a list)
*/
}
The id and value has to be added into a map checking if the ID is already present in the map, if not create a new entry.
The accessList might have many ID references with different value, in that case the value should be added to the entrySet of the already existing entry, the value would be a list with single value or multiple value.
public static void add(Map<String, Set<String>> map, String key, String value) {
map.compute(key, (id, values) -> {
(values = Optional.ofNullable(values).orElseGet(LinkedHashSet::new)).add(value);
return values;
});
}
For values it is better to use Set to exclude duplications.
Use computeIfAbsent() to initialise a List for the id if one doesn't exist already, then just add the value to that:
entitlementMap.computeIfAbsent(id, s -> new ArrayList<>()).add(value);
I'm checking to see if a key in my HashMap exists, if it does, I also want to check to see if any other keys have a value with the same name as that of the original key I checked for or not.
For example I have this.
System.out.println("What course do you want to search?");
String searchcourse = input.nextLine();
boolean coursefound = false;
if(hashmap.containsKey(searchcourse) == true){
coursefound = true;
}
This checks to see if the key exists in my hashmap, but now I need to check every single key's values for a specific value, in this case the string searchcourse.
Usually I would use a basic for loop to iterate through something like this, but it doesn't work with HashMaps. My values are also stored in a String ArrayList, if that helps.
You will want to look at each entry in the HashMap. This loop should check the contents of the ArrayList for your searchcourse and print out the key that contained the value.
for (Map.Entry<String,ArrayList> entries : hashmap.entrySet()) {
if (entries.getValue().contains(searchcourse)) {
System.out.println(entries.getKey() + " contains " + searchcourse);
}
}
Here are the relevant javadocs:
Map.Entry
HashMap entrySet method
ArrayList contains method
You can have a bi-directional map. E.g. you can have a Map<Value, Set<Key>> or MultiMap for the values to keys or you can use a bi-directional map which is planned to be added to Guava.
As I understand your question, the values in your Map are List<String>. That is, your Map is declares as Map<String, List<String>>. If so:
for (List<String> listOfStrings : myMap.values()) [
if (listOfStrings .contains(searchcourse) {
// do something
}
}
If the values are just Strings, i.e. the Map is a Map<String, String>, then #Matt has the simple answer.
I have this hashmap of students which stores the id, name and last name.
So I created this :
Map<Interger, HashMap<String,String>> students = new HashMap<>();
where the second hashmap stores the name and lastname.
My goal is to look for a student in a swing application, I succeed in searching with id because it's the key of the first hashmap, but i'd like to use all of them like this:
So my question is : If I want to search by name or last name, how can i get the value of the first hashmap and put it in a new hashmap ?
You can iterate on the hashmap like this :
private int searchByName(String s) {
for(Map.Entry<Integer, HashMap<String, String>> entry : students.entrySet()) {
HashMap student = entry.getValue(); // Hashmap containing first and lastname
if (student.containsKey(s)) // If name match
return entry.getKey(); // Return the student ID
}
return 0; // Student not found
}
For the lastname just use containsValue(s) instead of containsKey(s)
You can use the Google Collections API Guava for that specifically a BiMap
A bimap (or "bidirectional map") is a map that preserves the
uniqueness of its values as well as that of its keys. This constraint
enables bimaps to support an "inverse view", which is another bimap
containing the same entries as this bimap but with reversed keys and
values.
With this you'will be able to search using first name and last name. This BiMap will be value to your first parent hashmap.
I am not sure if the data structure is the best for your use-case but answering to your question, you should try using values() method which would return you the collection of values of the Map
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#values()
Collection res = studensts.values();
Iterator<HashMap<String, String>> i = res.iterator();
Map<String,String> resM = null;
while(i.hasNext()){
resM = i.next();
}
I have:
public static HashMap<String, String> CHILD_NAME_DOB = new HashMap<>();
Suppose the values in CHILD_NAME_DOB are:
<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>
I am trying to fetch the last key element from CHILD_NAME_DOB. That is, I want to fetch key alisha from the example above to temporary String name.
Also I want to know on how to fetch data by index.
Eg.: if int index = 2 , I want key "Neha" in String name
TIA.
Edit: DateOfBirth value (value data in CHILD_NAME_DOB) is dynamic and is unknown. So THIS LINK is not what I want.
Single line solution:
First note that the Java HashMap does not guarantee the order of entries. So each time you iterate over a HashMap, entries appear in different positions. You will need LinkedHashMap that guarantees the predictable iteration order.
Map<String, String> CHILD_NAME_DOB = new LinkedHashMap<>();
Get the key by index:
key = (new ArrayList<>(CHILD_NAME_DOB.keySet())).get(index)
Get the value by index:
CHILD_NAME_DOB.get(key)
Thanks to #Pentium10 for this answer.
And I little modified it according to my need.
String key="default";
Iterator myVeryOwnIterator = CHILD_NAME_DOB.keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
key=(String)myVeryOwnIterator.next();
//String value=(String)meMap.get(key);
}
Toast.makeText(viewEnterChildExp.getContext(), "Key: "+key , Toast.LENGTH_LONG).show();
I'm getting the last key element by this.
I'll update as soon I also get to find an easy way to key by index.
This way to get key....
public static String getHashMapKeyFromIndex(HashMap hashMap, int index){
String key = null;
HashMap <String,Object> hs = hashMap;
int pos=0;
for(Map.Entry<String, Object> entry : hs.entrySet())
{
if(index==pos){
key=entry.getKey();
}
pos++;
}
return key;
}
You can also use an ArrayMap instead of a HashMap. To get the value by index use:
ArrayMap.valueAt(index);
To get the Key at an index use:
ArrayMap.keyAt(index);
Fetching the "last" key and fetch by index is not supported by HashMap. You can use a LinkedHashMap and lookup the element with index 2 (or the last element) by iterating over it. But this will be a O(n) operation.
I suggest you use a List<Pair<String, String>> if the order of the keys/values is important to you and you wish to do index based lookup.
If both key based and index based lookup is important to you, you could use a combined data structure that consists of both a List and a HashMap, but note that removal of elements will be O(n).
You can create a class Child
public class Child(){
private String name;
private String number;
....
}
and then put this object in a List
public static List<Child> CHILD_NAME_DOB = new ArrayList<Child>(); // using LinkedList would defeat the purpose
in this way you can invoke the method get(int index), that returns the element at the specified position in this list.
In your example
<adam,15121990>
<roy,01051995>
<neha,05091992>
<alisha,11051992>
invoking CHILD_NAME_DOB.get(2) you'll get <neha,05091992>(as Child object)
HashMap does not have a concept of ordering, so getting the n-th entry does not make sense. You could use a TreeMap instead, which is ordered on its keys.
However, you should reconsider your model as you seem to have conflicting interests. On the one hand, accessing by index is typical for Lists, whereas accessing by key is typical for Maps. I'm not sure in which situation you'd want to do both.
If you really want to do both index and key accessing, you could write your own data structure that stores the data in a list combined with a mapping from key to index and vice versa. I would recommend against this, but if that's really what you want, then I think that's the best solution.
I know it is not the best solution, but what about this solution (pseudocode!). Just combine List and Map in one class.
public class UserBirthday {
private List<String> names = new ArrayList<>();
private Map<String, String> CHILD_NAME_DOB = new HashMap<String, String>();
public void add(String name, String bd) {
if (!CHILD_NAME_DOB.containsKey(name)) {
names.add(name);
}
CHILD_NAME_DOB.put(name, bd);
}
public String getByName(String name) {
return CHILD_NAME_DOB.get(name);
}
public String getByIndex(int index) {
return getByName(names.get(index)); // TODO: range test
}
public static void main(String[] args) {
UserBirthday ub = new UserBirthday();
ub.add("dit", "12345678");
ub.add("lea", "234239423");
ub.add("alex", "43534534");
ub.add("ted", "099098790");
System.out.println(ub.getByIndex(2));
System.out.println(ub.getByName("alex"));
}
}
You may get some problems if you remove an entry, but it should be just a suggestion.
for (String key : hmList.keySet()) {
String value = hmList.get(key);
Log.e("HashMap values", "key=" + key + " ,value=" + value);
}
If I pass the same key multiple times to HashMap’s put method, what happens to the original value? And what if even the value repeats? I didn’t find any documentation on this.
Case 1: Overwritten values for a key
Map mymap = new HashMap();
mymap.put("1","one");
mymap.put("1","not one");
mymap.put("1","surely not one");
System.out.println(mymap.get("1"));
We get surely not one.
Case 2: Duplicate value
Map mymap = new HashMap();
mymap.put("1","one");
mymap.put("1","not one");
mymap.put("1","surely not one");
// The following line was added:
mymap.put("1","one");
System.out.println(mymap.get("1"));
We get one.
But what happens to the other values? I was teaching basics to a student and I was asked this. Is the Map like a bucket where the last value is referenced (but in memory)?
By definition, the put command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types).
The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or null if none present), so you can determine what was there and maintain a reference if necessary.
More information here: HashMap Doc
You may find your answer in the javadoc of Map#put(K, V) (which actually returns something):
public V put(K key,
V value)
Associates the specified value with the specified key in this map
(optional operation). If the map
previously contained a mapping for
this key, the old value is replaced by
the specified value. (A map m is said
to contain a mapping for a key k if
and only if m.containsKey(k) would
return true.)
Parameters:
key - key with which the specified value is to be associated.
value - value to be associated with the specified key.
Returns:
previous value associated with specified key, or null if there was no
mapping for key. (A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.)
So if you don't assign the returned value when calling mymap.put("1", "a string"), it just becomes unreferenced and thus eligible for garbage collection.
it's Key/Value feature and you could not to have duplicate key for several values because when you want to get the actual value which one of values is belong to entered keyin your example when you want to get value of "1" which one is it ?!that's reasons to have unique key for every value but you could to have a trick by java standard lib :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DuplicateMap<K, V> {
private Map<K, ArrayList<V>> m = new HashMap<>();
public void put(K k, V v) {
if (m.containsKey(k)) {
m.get(k).add(v);
} else {
ArrayList<V> arr = new ArrayList<>();
arr.add(v);
m.put(k, arr);
}
}
public ArrayList<V> get(K k) {
return m.get(k);
}
public V get(K k, int index) {
return m.get(k).size()-1 < index ? null : m.get(k).get(index);
}
}
and you could to use it in this way:
public static void main(String[] args) {
DuplicateMap<String,String> dm=new DuplicateMap<>();
dm.put("1", "one");
dm.put("1", "not one");
dm.put("1", "surely not one");
System.out.println(dm.get("1"));
System.out.println(dm.get("1",1));
System.out.println(dm.get("1", 5));
}
and result of prints are :
[one, not one, surely not one]
not one
null
It replaces the existing value in the map for the respective key. And if no key exists with the same name then it creates a key with the value provided.
eg:
Map mymap = new HashMap();
mymap.put("1","one");
mymap.put("1","two");
OUTPUT
key = "1", value = "two"
So, the previous value gets overwritten.
The prior value for the key is dropped and replaced with the new one.
If you'd like to keep all the values a key is given, you might consider implementing something like this:
import org.apache.commons.collections.MultiHashMap;
import java.util.Set;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
public class MultiMapExample {
public static void main(String[] args) {
MultiHashMap mp=new MultiHashMap();
mp.put("a", 10);
mp.put("a", 11);
mp.put("a", 12);
mp.put("b", 13);
mp.put("c", 14);
mp.put("e", 15);
List list = null;
Set set = mp.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
list=(List)mp.get(me.getKey());
for(int j=0;j<list.size();j++)
{
System.out.println(me.getKey()+": value :"+list.get(j));
}
}
}
}
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
To your question whether the map was like a bucket: no.
It's like a list with name=value pairs whereas name doesn't need to be a String (it can, though).
To get an element, you pass your key to the get()-method which gives you the assigned object in return.
And a Hashmap means that if you're trying to retrieve your object using the get-method, it won't compare the real object to the one you provided, because it would need to iterate through its list and compare() the key you provided with the current element.
This would be inefficient. Instead, no matter what your object consists of, it calculates a so called hashcode from both objects and compares those. It's easier to compare two ints instead of two entire (possibly deeply complex) objects. You can imagine the hashcode like a summary having a predefined length (int), therefore it's not unique and has collisions. You find the rules for the hashcode in the documentation to which I've inserted the link.
If you want to know more about this, you might wanna take a look at articles on javapractices.com and technofundo.com
regards
Maps from JDK are not meant for storing data under duplicated keys.
At best new value will override the previous ones.
Worse scenario is exception (e.g when you try to collect it as a stream):
No duplicates:
Stream.of("one").collect(Collectors.toMap(x -> x, x -> x))
Ok. You will get: $2 ==> {one=one}
Duplicated stream:
Stream.of("one", "not one", "surely not one").collect(Collectors.toMap(x -> 1, x -> x))
Exception java.lang.IllegalStateException: Duplicate key 1 (attempted merging values one and not one)
| at Collectors.duplicateKeyException (Collectors.java:133)
| at Collectors.lambda$uniqKeysMapAccumulator$1 (Collectors.java:180)
| at ReduceOps$3ReducingSink.accept (ReduceOps.java:169)
| at Spliterators$ArraySpliterator.forEachRemaining (Spliterators.java:948)
| at AbstractPipeline.copyInto (AbstractPipeline.java:484)
| at AbstractPipeline.wrapAndCopyInto (AbstractPipeline.java:474)
| at ReduceOps$ReduceOp.evaluateSequential (ReduceOps.java:913)
| at AbstractPipeline.evaluate (AbstractPipeline.java:234)
| at ReferencePipeline.collect (ReferencePipeline.java:578)
| at (#4:1)
To deal with duplicated keys - use other package, e.g:
https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html
There is a lot of other implementations dealing with duplicated keys.
Those are needed for web (e.g. duplicated cookie keys, Http headers can have same fields, ...)
Good luck! :)
I always used:
HashMap<String, ArrayList<String>> hashy = new HashMap<String, ArrayList<String>>();
if I wanted to apply multiple things to one identifying key.
public void MultiHash(){
HashMap<String, ArrayList<String>> hashy = new HashMap<String, ArrayList<String>>();
String key = "Your key";
ArrayList<String> yourarraylist = hashy.get(key);
for(String valuessaved2key : yourarraylist){
System.out.println(valuessaved2key);
}
}
you could always do something like this and create yourself a maze!
public void LOOK_AT_ALL_THESE_HASHMAPS(){
HashMap<String, HashMap<String, HashMap<String, HashMap<String, String>>>> theultimatehashmap = new HashMap <String, HashMap<String, HashMap<String, HashMap<String, String>>>>();
String ballsdeep_into_the_hashmap = theultimatehashmap.get("firststring").get("secondstring").get("thirdstring").get("forthstring");
}
BTW, if you want some semantics such as only put if this key is not exist. you can use concurrentHashMap with putIfAbsent() function.
Check this out:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#put(K,%20V)
concurrentHashMap is thread safe with high performance since it uses "lock striping" mechanism to improve the throughput.
Yes, this means all the 1 keys with value are overwriten with the last added value and here you add "surely not one" so it will display only "surely not one".
Even if you are trying to display with a loop, it will also only display one key and value which have same key.
HashMap<Emp, Emp> empHashMap = new HashMap<Emp, Emp>();
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp());
empHashMap.put(new Emp(1), new Emp());
System.out.println(empHashMap.size());
}
}
class Emp{
public Emp(){
}
public Emp(int id){
this.id = id;
}
public int id;
#Override
public boolean equals(Object obj) {
return this.id == ((Emp)obj).id;
}
#Override
public int hashCode() {
return id;
}
}
OUTPUT : is 1
Means hash map wont allow duplicates, if you have properly overridden equals and hashCode() methods.
HashSet also uses HashMap internally, see the source doc
public class HashSet{
public HashSet() {
map = new HashMap<>();
}
}