LinkedHashMap中根据value读取key值

来源:互联网 发布:数据库中的关系 编辑:程序博客网 时间:2024/05/23 19:15

hashmap中key值是唯一的,但value是不唯一的,所以是没有办法通过像get(key)取value值一样直接取key的 。但是可以自己写个方法来实现:

以下为本人亲测,当你使用LinkedHashMap来实例化一个map对象,然后存储的顺序就是你输入时候的顺序,这样当你使得value的值不重复时,就可以使用这个方法啦,只要改一下下实例化的对象名字就ok。

private static LinkedHashMap<Integer, Character> map;//存储字符及其对应的编码

public static void hashMap(int first)//first表示其实编码,总共存储94个,对map进行初始化内嵌
{

 map=new LinkedHashMap<Integer,Character>();
int key[]=new int[num];//定义数组存储键的值
int k=0;
for(int i=first;i<=(num-1+first);i++)
{
key[k]=i; 
k++;
}
//定义数组存储字符
char Value[]={'!','"','#','$','%','&','’','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~'};
for(int j=0;j<num;j++)
{
map.put(key[j], Value[j]);
}

//根据value取key值
public static int getKey(char value)//根据字符得到对应的编码
{
int key = 0;
 Set<Map.Entry<Integer, Character>> set = map.entrySet();  
        for(Entry<Integer, Character> entry : set){  
            if(entry.getValue().equals(value)){  
                key = entry.getKey();  
                break;  
            }  
        }  

return key;
}




0 0
原创粉丝点击