-3

I want to search element in user defined key in java hashmap for example

It is possible to search in this example like hm.containsKey(new Price("Banana", 20)), but in this example i want to search by specific data member like price or item wise.

public class MyObjectKeySearch {
 
public static void main(String a[]){
         
        HashMap<Price, String> hm = new HashMap<Price, String>();
        hm.put(new Price("Banana", 20), "Banana");
        hm.put(new Price("Apple", 40), "Apple");
        hm.put(new Price("Orange", 30), "Orange");
        printMap(hm);
        Price key = new Price("Banana", 20);
        System.out.println("Does key available? "+hm.containsKey(key));
    }
     
    public static void printMap(HashMap<Price, String> map){
         
        Set<Price> keys = map.keySet();
        for(Price p:keys){
            System.out.println(p+"==>"+map.get(p));
        }
    }
}
 
class Price{
     
    private String item;
    private int price;
     
    public Price(String itm, int pr){
        this.item = itm;
        this.price = pr;
    }
     
    public int hashCode(){
        System.out.println("In hashcode");
        int hashcode = 0;
        hashcode = price*20;
        hashcode += item.hashCode();
        return hashcode;
    }
     
    public boolean equals(Object obj){
        System.out.println("In equals");
        if (obj instanceof Price) {
            Price pp = (Price) obj;
            return (pp.item.equals(this.item) && pp.price == this.price);
        } else {
            return false;
        }
    }
     
    public String getItem() {
        return item;
    }
    public void setItem(String item) {
        this.item = item;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
     
    public String toString(){
        return "item: "+item+"  price: "+price;
    }
}
2
  • please post your code Commented Nov 25, 2015 at 14:46
  • I have posted my code in this example i can search by new Price(item, price), but i want to search by items or price only Commented Nov 25, 2015 at 14:51

1 Answer 1

1

Yes:

hm.containsKey(new Price("Banana", 20))

is possible and behaves the way you would expect.

And No: You cannot do any contains-check based on members of your key objects that does not involve iterating over the key set of the HashMap. containsKey(paramKey) returns true if there is a key in the appropriate "hash bucket" identified by key.hashCode() that is equal to paramKey. The value of hashCode() obscures member values. You could use a more complex data structure like a nested HashMap:

HashMap<String, HashMap<Integer, String>> hm;

Where you use item Strings as keys in the outer Map and price Integers as keys in the inner Map. Then you can query like:

(hm.containsKey("Banana") && hm.get("Banana").containsKey(20))

which will be much more efficient than iterating over a large set of Price objects. This, however, does still not allow you to query efficiently for all inner entries with a specific price (Integer) without iterating over the outer key set. You can reverse inner and outer key types accordingly though:

HashMap<Integer, HashMap<String, String>> hm;

You can, of course, create your own class that encapsulates the functionality of both:

/* Provides constant time (O(1)) Price lookup by item and price */
class PriceMap {
    private HashMap<String, Set<Price>> stringMap;
    private HashMap<Integer, Set<Price>> intMap;

    public PriceMap() {
        stringMap = new HashMap<String, Set<Price>>();
        intMap = new HashMap<Integer, Set<Price>>();
    }

    public void add(Price price) {
        String item = price.getItem()
        if (!stringMap.containsKey(item))
            stringMap.put(item, new HashSet<Price>());
        stringMap.get(item).add(Price);
        int price = price.getPrice()
        if (!intMap.containsKey(price))
            intMap.put(price, new HashSet<Price>());
        intMap.get(price).add(Price);
    }

    public Set<Price> prices(int price) {
        return intMap.containsKey(price) ? intMap.get(price) : new HashSet<Price>(); 
    }

    public boolean containsKey(int price) {
        return intMap.containsKey(price); 
    }

    public Set<Price> prices(String item) {
        return stringMap.containsKey(item) ? stringMap.get(item) : new HashSet<Price>(); 
    }

    public boolean containsKey(String item) {
        return stringMap.containsKey(item); 
    }

}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks ,can you please give me some source or links for this to explaining more in details
In this thread, there is some explanation: stackoverflow.com/questions/5056708/…, otherwise general java API documentation: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
i dont want to use nested hashmap, i just want to explaination of you're menstioning "NO section" in your answer
Keys in a HashMap are looked up by their hashCode() function which returns an int value that obscures the key's members. Thus, finding a key with a particular member value requires you to look at each key and observe that member. I will edit my answer to specify that...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.