Java 关于HashMap根据value反向获取key值

Map中是一个key有且只有一个value.
但是一个value可以对应多个key值.
一般都是通过key,然后map.get(key)获得到value.

如果想要反向通过value获得key的值,提供以下方法:


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 map = new HashMap();
		map.put("1", "A");
		map.put("2", "A");
		map.put("3", "B");
		map.put("4", "A");
		map.put("5", "A");

		String value = "A";
		ArrayList arr = FromValueGetKey(map, value);
		if (!arr.isEmpty()) {
			for (int i = 0; i < arr.size(); i++) {
				System.out.println(arr.get(i));
			}
		}
	}

	private static ArrayList FromValueGetKey(Map map,
			String value) {
		Set set = map.entrySet();
		ArrayList arr = new ArrayList();
		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;
	}
}


在控制台输出的结果显示:

1
2
4
5



你可能感兴趣的:(Java)