HashMap嵌套ArrayList
package com.bigdat.java.day22;
import java.util.*;
/*
HashMap嵌套ArrayList
*/
public class HashMapAndArrayList {
public static void main(String[] args) {
//创建 HashMap 班级集合
HashMap<ArrayList<Student1>, String> asMap = new HashMap<>();
//创建 ArrayList集合
ArrayList<Student1> pt = new ArrayList<Student1>();
ArrayList<Student1> jy = new ArrayList<Student1>();
ArrayList<Student1> hh = new ArrayList<Student1>();
//创建普通班学生
Student1 s1 = new Student1("普通一",21);
Student1 s2 = new Student1("普通二",22);
Student1 s3 = new Student1("普通三",23);
//创建精英班学生
Student1 s4 = new Student1("精英四",24);
Student1 s5 = new Student1("精英五",25);
//创建豪华班学生
Student1 s6 = new Student1("豪华六",26);
//添加普通学生
pt.add(s1);
pt.add(s2);
pt.add(s3);
//添加精英学生
jy.add(s4);
jy.add(s5);
//添加豪华学生
hh.add(s6);
//添加班级到集合中
asMap.put(pt, "普通班");
asMap.put(jy, "精英班");
asMap.put(hh, "豪华班");
//开始遍历大的班级集合
//创建 键值对 的对象
Set<Map.Entry<ArrayList<Student1>, String>> entries = asMap.entrySet();
//创建 键值对 迭代器
Iterator<Map.Entry<ArrayList<Student1>, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<ArrayList<Student1>, String> next = iterator.next();
ArrayList<Student1> key = next.getKey();
String value = next.getValue();
//创建学生的迭代器
Iterator<Student1> iterator1 = key.iterator();
while(iterator1.hasNext()){
Student1 next1 = iterator1.next();
String name = next1.getName();
int age = next1.getAge();
System.out.println("班级:"+value+",姓名:"+name+",年龄:"+age);
}
}
}
}
ArrayList中嵌套HashMap
package com.bigdat.java.day22;
import java.util.*;
/*
ArrayList中嵌套HashMap
*/
public class ArrayListAndHashMap {
public static void main(String[] args) {
//创建大的班级集合
ArrayList<HashMap<Student1,String>> list = new ArrayList<>();
//创建各班级集合
HashMap<Student1, String> pt = new HashMap<>();
HashMap<Student1, String> jy = new HashMap<>();
HashMap<Student1, String> hh = new HashMap<>();
//创建普通班学生
Student1 s1 = new Student1("普通一",21);
Student1 s2 = new Student1("普通二",22);
Student1 s3 = new Student1("普通三",23);
//创建精英班学生
Student1 s4 = new Student1("精英四",24);
Student1 s5 = new Student1("精英五",25);
//创建豪华班学生
Student1 s6 = new Student1("豪华六",26);
//学生添加入班级
pt.put(s1, "普通班");
pt.put(s2, "普通班");
pt.put(s3, "普通班");
jy.put(s4, "精英班");
jy.put(s5, "精英班");
hh.put(s6, "豪华班");
//将班级远元素加入
list.add(pt);
list.add(jy);
list.add(hh);
//开始遍历
for (HashMap<Student1, String> student1StringHashMap : list) {
Set<Map.Entry<Student1, String>> entries = student1StringHashMap.entrySet();
for (Map.Entry<Student1, String> entry : entries) {
Student1 key = entry.getKey();
String value = entry.getValue();
String name = key.getName();
int age = key.getAge();
System.out.println("班级:"+value+",姓名:"+name+",年龄:"+age);
}
}
}
}