欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java中关于Map的三种遍历方法详解

程序员文章站 2023-12-14 16:14:46
map的三种遍历方法!集合的一个很重要的操作---遍历,学习了三种遍历方法,三种方法各有优缺点~~复制代码 代码如下:/* * to change this te...
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 + '}';
    }
}

上一篇:

下一篇: