Detailed explanation of the three traversal methods of Map in Java

  • 2020-04-01 02:00:42
  • OfStack

Map's three traversal methods!
Set of a very important operation -- traversal, learned three kinds of traversal methods, three methods have advantages and disadvantages


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;

public class TestMap {
    public static void main(String[] args) {
        Map<String, Student> map = new HashMap<String, Student>();
        Student s1 = new Student(" Sung river ", "1001", 38);
        Student s2 = new Student(" Jun-yi lu ", "1002", 35);
        Student s3 = new Student(" With wu ", "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);
    }
//The most common method of traversal, the most common is the most commonly used, although not complex, but very important, this is the most familiar to us, not to say!
    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());
        }
    }
//Use keyset to traverse, its advantage is that you can according to the key you want the values you want, more flexible!!
    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));
        }
    }
  //A more complex kind of traversal is here, ha ha ~~ he is very violent, its flexibility is too strong, want what can get what ~~
    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 + '}';
    }
}

Related articles: