程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java中關於Map的三種遍歷辦法詳解

java中關於Map的三種遍歷辦法詳解

編輯:關於JAVA

java中關於Map的三種遍歷辦法詳解。本站提示廣大學習愛好者:(java中關於Map的三種遍歷辦法詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是java中關於Map的三種遍歷辦法詳解正文


map的三種遍歷辦法!
聚集的一個很主要的操作---遍歷,進修了三種遍歷辦法,三種辦法各有優缺陷~~

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.tsp2c.liubao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
 *
 * @author Administrator
 */
public class TestMap {
    public static void main(String[] args) {
        Map<String, Student> map = new HashMap<String, Student>();
        Student s1 = new Student("宋江", "1001", 38);
        Student s2 = new Student("盧俊義", "1002", 35);
        Student s3 = new Student("吳用", "1003", 34);

        map.put("1001", s1);
        map.put("1002", s2);
        map.put("1003", s3);
        Map<String, Student> subMap = new HashMap<String, Student>();
        subMap.put("1008", new Student("tom", "1008", 12));
        subMap.put("1009", new Student("jerry", "1009", 10));
        map.putAll(subMap);
        work(map);
        workByKeySet(map);
        workByEntry(map);
    }
//最慣例的一種遍歷辦法,最慣例就是最經常使用的,固然不龐雜,但很主要,這是我們最熟習的,就不多說了!!
    public static void work(Map<String, Student> map) {
        Collection<Student> c = map.values();
        Iterator it = c.iterator();
        for (; it.hasNext();) {
            System.out.println(it.next());
        }
    }
//應用keyset停止遍歷,它的長處在於可以依據你所想要的key值獲得你想要的 values,更具靈巧性!!
    public static void workByKeySet(Map<String, Student> map) {
        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            System.out.println(map.get(s));
        }
    }
  //比擬龐雜的一種遍歷在這裡,呵呵~~他很暴力哦,它的靈巧性太強了,想獲得甚麼就可以獲得甚麼~~
    public static void workByEntry(Map<String, Student> map) {
        Set<Map.Entry<String, Student>> set = map.entrySet();
        for (Iterator<Map.Entry<String, Student>> it = set.iterator(); it.hasNext();) {
            Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next();
            System.out.println(entry.getKey() + "--->" + entry.getValue());
        }
    }
}
class Student {
    private String name;
    private String id;
    private int age;
    public Student(String name, String id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" + "name=" + name + "id=" + id + "age=" + age + '}';
    }
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved