ContainsValue vs equals method TreeMap

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>();
    archivio.put("WaltDisney", "DonaldDuck");
    archivio.put("Shakespeare", "Amleto");
    archivio.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 key is: "+ oldbooks.get(k)
            +" The Value is: "+ k);
        }
    }

I notice that in this way i enter in the if but it dont print nothing. If i change my if condition and i put:

if(title.equals(oldbooks.get(k))

Now it function very well. So why i cant 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.

1 answer

  • answered 2019-12-14 17:31 Shivam Puri

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