在map集合中通过value怎么得到key

2025-05-09 02:38:28
推荐回答(2个)
回答1:

package test;import java.util.*;/** 取得Map中的key的集合用的方法是keySet,返回的是Set,
* 取得Map中的value的集合用的方法是values,返回的是Collect。
* 值得一提的是,本题中是HashMap,如果改为TreeMap,keySet()方法返回的便会按着字母顺序排列,原因很简单,因为在TreeMap中即时按着这个顺序排列的。

*/public class Test_Map {
public static void main(String[] args) throws Exception {
Map map = new HashMap();
map.put("one", 1);map.put("two", 2);
map.put("three", 3);
//得到value的方法
System.out.println("========得到value的方法========");
Collection c = map.values();
System.out.println(c);
Iterator iter1 = (Iterator)map.values().iterator();
while(iter1.hasNext()){
System.out.println(iter1.next());}//得到key的方法
System.out.println("========得到key的方法========");
Collection s = map.keySet();
System.out.println(s);
Iterator iter2 = (Iterator)map.keySet().iterator();

回答2:

只能通过KEY获取VALUE