有时,我们想获得Map中所有Key值集合。有时,我们又需要提取出Map中所有value的值。
很简单,就用两个Map自带的方法即可轻松实现:
  1. Set Map.keySet():获得Map中所有Key的集合;
  2. Collection Map.values() : 获得Map中所有value的集合;

Show me the code:

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

public class MapTest {
    public static void main(String[] args) {
        LinkedHashMap<String, Integer> stringIntegerLinkedHashMap = new LinkedHashMap<String, Integer>();
        stringIntegerLinkedHashMap.put("a",1);
        stringIntegerLinkedHashMap.put("b",2);
        stringIntegerLinkedHashMap.put("c",3);
        stringIntegerLinkedHashMap.put("d",4);

        Set<String> keySet = stringIntegerLinkedHashMap.keySet();
        Collection<Integer> valueSet = stringIntegerLinkedHashMap.values();
        Iterator<String> keyIterator = keySet.iterator();
        Iterator<Integer> valueIteator = valueSet.iterator();
        while (keyIterator.hasNext() ){
            System.out.println(keyIterator.next() + "  " + valueIteator.next());
        }

    }
}

运行结果如下:
a 1
b 2
c 3
d 4