The use of java Map interface

Create a new student class, including member variables including student ID, name and age, and then create a test class with the student ID as the key and the student class object as the value, save it to the Map, and realize the output. Here we mainly talk about output access. When the core is the iterator.

package helloworld;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class StudentTest {

	public static void main(String[] args) {
		List<Student> stu = new ArrayList<Student>();
		Student stu1 = new Student("1000", "aaa", 18);
		Student stu2 = new Student("1001", "bbb", 19);
		Student stu3 = new Student("1002", "ccc", 18);
		Student stu4 = new Student("1001", "ddd", 20);
		
		stu.add(stu1);
		stu.add(stu2);
		stu.add(stu3);
		stu.add(stu4);
		
		Iterator<Student> it = stu.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
		Collections.sort(stu, new Comparator<Student>(){

			@Override
			public int compare(Student o1, Student o2) {
				if(o1.id.compareTo(o2.id) == 0){
					return o1.age-o2.age;
				}
				return o1.id.compareTo(o2.id);
			}	
		});
		System.out.println("-----------");	
		Iterator<Student> it1 = stu.iterator();
		while(it1.hasNext()){
			System.out.println(it1.next());
		}
		
	}
}



package helloworld;

import java.util. *;
import java.util.Map.Entry;

public class StudentTest3 {

	public static void main(String[] args) {
		Map<String, Student> map = new HashMap<String, Student>();
		
		Student stu1 = new Student("1000", "aaa", 18);
		Student stu2 = new Student("1001", "bbb", 19);
		Student stu3 = new Student("1002", "ccc", 18);
		Student stu4 = new Student("1003", "ddd", 20);
		
		map.put(stu1.id, stu1);
		map.put(stu2.id, stu2);
		map.put(stu3.id, stu3);
		map.put(stu4.id, stu4);
		
		
		//1\Using key-value pairs
		Set<String> keyset = map.keySet();
		Iterator<String> it = keyset.iterator();
		while(it.hasNext()){
			String nextkey = it.next();
			Student obj = map.get(nextkey);
			System.out.println(nextkey +"--"+obj);
		}
		System.out.println("************");
		//2 Use the key-value pair collection
		Set<Entry<String, Student>> entrySet = map.entrySet();
		Iterator<Entry<String, Student>> it1 = entrySet.iterator();
		while(it1.hasNext()){
			Entry<String, Student> entry = it1.next();
			String id = entry.getKey();
			Student stu = entry.getValue();
			System.out.println(id+"---"+stu);
		}
		System.out.println("************");
		//3
		Collection<Student> col = map.values();
		Iterator<Student> it2 = col.iterator();
		while(it2.hasNext()){
			Student stu0 = it2.next();
			System.out.println("----"+stu0);
		}
	}

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325735326&siteId=291194637