但是一个value可以对应多个key值.
一般都是通过key,然后map.get(key)获得到value.
如果想要反向通过value获得key的值,提供以下方法:
- <span style="font-size:18px;">package com.jglz.qing.map;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- public class MapValueGetKeyDemo {
- public static void main(String[] args) {
- Map<String, String> map = new HashMap<String, String>();
- map.put("1", "A");
- map.put("2", "A");
- map.put("3", "B");
- map.put("4", "A");
- map.put("5", "A");
- String value = "A";
- ArrayList<String> arr = FromValueGetKey(map, value);
- if (!arr.isEmpty()) {
- for (int i = 0; i < arr.size(); i++) {
- System.out.println(arr.get(i));
- }
- }
- }
- private static ArrayList<String> FromValueGetKey(Map<String, String> map,
- String value) {
- Set set = map.entrySet();
- ArrayList<String> arr = new ArrayList<String>();
- Iterator it = set.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- if (entry.getValue().equals(value)) {
- String s = (String) entry.getKey();
- arr.add(s);
- }
- }
- return arr;
- }
- }</span>
1
2
4
5