四種方法遍歷map集合--------day20

1.分析以下需求,並用代碼實現:

(1)定義一個學生類Student,包含屬性:姓名(String name)、年齡(int age)
(2)定義Map集合,用Student對象作爲key,用字符串(此表示表示學生的住址)作爲value
(3)利用四種方式遍歷Map集合中的內容,格式:key::value
package cn.demo02;
/*
 * 定義學生類
 */
public class Student {
	private String name;
	private int age;
	
	public Student(){}
	
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return  name+"   "+ age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
}
package cn.demo02;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/*
 * 1.分析以下需求,並用代碼實現:
	(1)定義一個學生類Student,包含屬性:姓名(String name)、年齡(int age)
	(2)定義Map集合,用Student對象作爲key,用字符串(此表示表示學生的住址)作爲value
	(3)利用四種方式遍歷Map集合中的內容,格式:key::value
 */
public class HomeWork {
	public static void main(String[] args) {
		Student s1 = new Student();
		Student s2 = new Student();
		Student s3 = new Student();
		s1.setName("張三");
		s1.setAge(18);
		
		s2.setName("李四");
		s2.setAge(20);
		
		s3.setName("趙柳");
		s3.setAge(25);
		
		ArrayList<Student> array = new ArrayList<Student>();
		array.add(s1);
		array.add(s2);
		array.add(s3);
		
		HashMap<Student, String> hm = new HashMap<Student, String>();
		hm.put(s1, "北京市朝陽區");
		hm.put(s2, "上海市浦東新區");
		hm.put(s3, "廣州市");
		
		function_3(hm,array);
		
		
	
	}
	public static void function_1(HashMap<Student, String> hm,ArrayList<Student> array){
		for (int i = 0; i < hm.size(); i++) {
			Student s= array.get(i);
			System.out.print(s+":: ");
			System.out.println(hm.get(s));
		}	
		
	}

	public static void function_2(HashMap<Student, String> hm){
		for (Student s:hm.keySet()) {
			System.out.println(s+"::"+hm.get(s));
		}
	}
	
	public static void function_3(HashMap<Student, String> hm,ArrayList<Student> array){
	
		Iterator ita = array.iterator();
		while(ita.hasNext()){
		Object s = ita.next();
			System.out.println(s+"::"+hm.get(s));
		}
	}
	
	public static void function_4(HashMap<Student, String> hm,ArrayList<Student> array){
		for(String s:hm.values()){
			for (int i = 0; i < array.size(); i++) {
				System.out.println(array.get(i)+"::"+s);
			}
		}
	}
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章