i wanto to print the selected key and value that arrive here from a scanner object. I tried in this way and i notice a difference:
TreeMap<String, String> oldbooks = new TreeMap<String,String>();
oldbooks.put("WaltDisney", "DonaldDuck");
oldbooks.put("Shakespeare", "Amleto");
oldbooksput("Dickens", "OliverTwist");
Scanner in = new Scanner(System.in);
String title = in.next();
boolean found = oldbooks.containsValue(title);
for(String k : oldbooks.keySet())
{
if(found) {
System.out.print("The value is : "+ oldbooks.get(k)
+" The Key is: "+ k);
}
}
I notice that in this way i obtain every keys and every values, i want the right key and the right value. If i change my if condition and i put:
if(title.equals(oldbooks.get(k))
Now it function very well. So why i can't print the specified value and key with the first solution? i know that .equals give me true and false just like containsValue. Thank you in advance.
As per your edit, you are putting the values in a different map archivio
and trying to search for it in a different map oldbooks
.
Was that intentional? Or perhaps that is the problem in your code!
Below code is working fine for me;
TreeMap<String, String> oldbooks = new TreeMap<>();
oldbooks.put("WaltDisney", "DonaldDuck");
oldbooks.put("Shakespeare", "Amleto");
oldbooks.put("Dickens", "OliverTwist");
Scanner in = new Scanner(System.in);
String title = in.next();
boolean found = oldbooks.containsValue(title);
for(String k : oldbooks.keySet())
{
if(found) {
System.out.print("The value is: "+ oldbooks.get(k)
+" The Key is: "+ k);
}
}
When I run this in my IDE, I simply have to type DonaldDuck
in the console and I am getting the expected result (prints all key-value pairs).
Also, FYI, you have been printing incorrect key-values in your system.out.print statement.
The key is k
and the value is what you get using oldbooks.get(k)
. Not the other way around. (As pointed by @dan1st in the first comment).