Map<K,V> map = new HashMap<>();
Set<Map.Entry<K,V>> set = map.entrySet(); //Elements stored in the set is an entry
map.keySet(); //a set ofmap's key
map.values(); //return Collection object.
2. Map详解
package com.fqy.blog;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
class Faculty {
private String name;
public Faculty(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class MapDemo {
public static void main(String[] args) {
Random random = new Random();
Faculty f1 = new Faculty("a");
Faculty f2 = new Faculty("b");
Faculty f3 = new Faculty("c");
Faculty f4 = new Faculty("d");
Faculty f5 = new Faculty("e");
// Default value of object array is NULL
Integer[] arr = new Integer[5];
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(100) * (random.nextBoolean() ? 1 : -1);
Map<Faculty, Integer> map = new HashMap<>();
map.put(f1, arr[0]);
map.put(f2, arr[1]);
map.put(f3, arr[2]);
map.put(f4, arr[3]);
map.put(f5, arr[4]);Set<Faculty> set = map.keySet();Set<Map.Entry<Faculty, Integer>> entrySet = map.entrySet();
Collection<Integer> c = map.values();
System.out.println(c);
for (Faculty f : set)
System.out.print(f + " ");
System.out.println();
for (Map.Entry<Faculty, Integer> entry : entrySet)
System.out.print(entry + " ");
System.out.println();
// Iteration 1:
for (Faculty f : set)
System.out.print(map.get(f) + " ");
System.out.println();
// Iteration 2:
for (Map.Entry<Faculty, Integer> entry : map.entrySet())
System.out.print(entry.getKey() + "->" + entry.getValue() + " ");
System.out.println();
}
}
//Running result:
[-93, -34, -79, 70, -14]
c d b a e
c=-93 d=-34 b=-79 a=70 e=-14
-93 -34 -7970 -14
c->-93 d->-34 b->-79 a->70 e->-14