How to display and remove values in dictionary which holds duplicate keys

Viewed 161

In this program I want to display (textview) as Banana as the key value is. And I want to remove that key value 2 which holds banana. and i want to display (textview2) as Orange .Is there any alterative there? Could u give me a solution to obtain this? Thanks in advance

int a = 1;
int b = 2;
int c = 3;
int d = 2;

Hashtable<Integer, String> my_dict = new Hashtable <Integer, String>();

my_dict.put(a, "Apple");
my_dict.put(b, "Banana");
my_dict.put(c, "Orange");
my_dict.put(d, "Grapes");

textView.setText(my_dict.get(1));//displays Apple
my_dict.remove(1);//removes Apple

textView2.setText(my_dict.get(2));//displays Grapes
my_dict.remove(2);//removes Grapes

textView3.setText(my_dict.get(2));//displays Banana
my_dict.remove(2);//removes Banana   

But i dont want to alter that duplicate keys. I want to iterate through each values of key and i want to get that datas which is stored in that key ...and i want to delete that key and value ...and after i want to check for another. (In this case)

1 Answers

A HashTable maintains the uniqueness of keys i.e. when you will try to add an element with the existing key, the old value will be replaced with the new one. You can understand it with your own example given below:

import java.util.Hashtable;

public class Main {
    public static void main(String[] args) {
        int a = 1;
        int b = 2;
        int c = 3;
        int d = 2;

        Hashtable<Integer, String> my_dict = new Hashtable <Integer, String>();

        my_dict.put(a, "Apple");
        my_dict.put(b, "Banana");
        my_dict.put(c, "Orange");
        my_dict.put(d, "Grapes");

        System.out.println(my_dict);
    }
}

Output:

{3=Orange, 2=Grapes, 1=Apple}

As you can see, Grape has replaced Banana because it has the same key as that of Banana.

If you have a requirement to keep both Grape and Banana with the same id/key, you can implement your custom type something like:

class Item {
    private int id;
    private String name;
    //Constructors, getters and setters 
}

And then, add the instances of Item to a List e.g.

List <Item> list = new ArrayList<Item>();
list.add(new Item(1, "Apple"));
list.add(new Item(2, "Banana"));
list.add(new Item(3, "Orange"));
list.add(new Item(2, "Grape"));

You can create some utility methods (an example is given below) to retrieve the required item from the List.

public Item getItemByName(List<Item> list, String itemName) {
    Item item = null;
    for(Item e: list){
        if(e.getName().equalsIgnoreCase(itemName)){
            item = e;
            break;
        }
    }
    return item;
}
Related