public class Test1 {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("1","a");
map.put("2","b");
map.put("3","c");
map.put("4","d");
map.put("5","e");
map.put("6","f");
map.put("7","g");
// keySet()方法
Set set = map.keySet();
System.out.println(set);
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
// values()方法
Collection collection = map.values();
System.out.println(collection);
for (Object o : collection){
System.out.println(o);
}
// entrySet()方法
Set entrySet = map.entrySet();
System.out.println(entrySet);
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()){
Map.Entry entry = (Map.Entry)iterator2.next();
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
}
TreeMap
应为要根据key排序,所以key必须同一类型
排序分为自然排序 和 定制排序
public class Test2 {
public static void main(String[] args) {
// 定制排序 (从大到小)
Comparator comparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof User && o2 instanceof User){
User u1 = (User) o1;
User u2 = (User) o2;
return -Integer.compare(u1.getAge(),u2.getAge());
}else{
throw new RuntimeException("Yes, Error!");
}
}
};
TreeMap treeMap = new TreeMap(comparator);
// 自然排序(从小到大)
//TreeMap treeMap = new TreeMap();
User user1 = new User(33);
User user2 = new User(23);
User user3 = new User(90);
User user4 = new User(45);
User user5 = new User(-12);
User user6 = new User(34);
treeMap.put(user1,98);
treeMap.put(user2,85);
treeMap.put(user3,34);
treeMap.put(user4,123);
treeMap.put(user5,-23);
treeMap.put(user6,128);
Set set = treeMap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
Map.Entry entry = (Map.Entry)iterator.next();
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
}
public class User implements Comparable{
private int age ;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(int age) {
this.age = age;
}
public User() {
}
@Override
public int compareTo(Object o) {
if (o instanceof User){
User u = (User) o;
return Integer.compare(this.age,u.age);
}else{
throw new RuntimeException("Yes, Error!");
}
}
@Override
public String toString() {
return "User{" +
"age=" + age +
'}';
}
}