Map的基本用法(Java)

package home.collection.arr;

import java.awt.Window.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class HomeworkMap2 {
    public static void main(String[] args) {
        // 创建Map
        Map<Integer,Student> map = new HashMap<Integer,Student>();
        createStudets(20, map);
//       System.out.println(map);
        
        List<Integer> scoreList = new ArrayList<Integer>();
        getAllScore(scoreList, map,1,null);
        
        // 排序
        sortByScore(scoreList);
        
        // 取前三位
        int[] maxScores = new int[3];
        for (int i = 0; i < maxScores.length; i++) {
            if (scoreList.get(i)>0) {
                maxScores[i]=scoreList.get(i);
//                System.out.println(maxScores[i]);
            }
        }
        
        getAllScore(scoreList, map, 2, maxScores);

    }
    
    /**
     * @param count  创建学生的个数
     * @param map    存放学生的Map
     */
    public static void createStudets(int count,Map<Integer,Student> map){
        // 创建一部分students
        for (int i = 0; i < count; i++) {
            Student stu = new Student("lf"+i, 75+i);
            // student被添加到map中
            map.put(stu.getNumber(), stu);
        }
    }
    /**
     * 
     * @param scoreList
     * @param map
     * @param method
     * @param maxScores
     */
    public static void getAllScore(List<Integer> scoreList,Map<Integer,Student> map,int method,int[] maxScores) {
        // 从Map取出score放进newList
        // 遍历
        // 取出Map中的键值对
        Set<Entry<Integer, Student>> entry = map.entrySet();
//                System.out.println(entry);
        // 遍历set(就是遍历Map)
        Iterator<Entry<Integer, Student>> it = entry.iterator();
        while (it.hasNext()) {
            // Entry key-value
            Entry<Integer, Student> e =  it.next();
            Student s = e.getValue();
            if (method == 1) {
                scoreList.add(s.getScore());
            }else if (method == 2) {
                // 判断
                for (int i = 0; i < maxScores.length; i++) {
                    if (s.getScore() == maxScores[i]) {
                        System.out.println("第"+(i+1)+"名:"+s.getName()+"  分数:"+s.getScore());
                    }
                }
            }
            
        }
//        System.out.println(scoreList);
    }
    /**
     * 排序
     */
    public static void sortByScore(List<Integer> scoreList){
        Collections.sort(scoreList, new Comparator<Integer>() {
            public int compare(Integer num1,Integer num2) {
                return num2-num1;
            }
        });
    }
}
原文地址:https://www.cnblogs.com/lantu1989/p/6078759.html