- 使用HashMap存储一行数据
- 将每一行数据存入ArrayList中
- 使用keySet和entrySet分别进行数据的遍历
package com.wd.container;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 测试使用Map和List共同使用下实现表格数据的存储
* @author Steven
*
*/
public class TestMapAndList{
public static void main(String[] args) {
HashMap<String, Object> row1 = new HashMap<>();
row1.put("id", 123);
row1.put("姓名", "qwer");
row1.put("薪水", 20000);
row1.put("入职日期",new GregorianCalendar(2000,5,6).toString());
HashMap<String, Object> row2 = new HashMap<>();
row2.put("id", 234);
row2.put("姓名", "asfd");
row2.put("薪水", 50000);
row2.put("入职日期", new GregorianCalendar(1996,5,8).toString());
HashMap<String, Object> row3 = new HashMap<>();
row3.put("id",345);
row3.put("姓名", "zxcv");
row3.put("薪水", 62222);
row3.put("入职日期", new GregorianCalendar(3000,6,888).toString());
HashMap<String, Object> row4 = new HashMap<>();
row4.put("id", 456);
row4.put("姓名", "rtyu");
row4.put("薪水", 6000);
row4.put("入职日期", new GregorianCalendar(5222, 65, 222).toString());
ArrayList<Map<String,Object>> arrayList = new ArrayList<>();
arrayList.add(row1);
arrayList.add(row2);
arrayList.add(row3);
arrayList.add(row4);
/*
* 使用keySet进行遍历
*/
for(Map<String,Object> m:arrayList){
Set<String> keySet = m.keySet();
for(Iterator<String> i = keySet.iterator();i.hasNext();){
String s=i.next();
System.out.println(s+"="+m.get(s));
}
}
/*
* 使用entrySet进行遍历
*/
// for(Map<String,Object> m:arrayList){
// Set<Entry<String, Object>> entrySet = m.entrySet();
// for(Iterator<Entry<String, Object>> i=entrySet.iterator();i.hasNext();){
// System.out.println(i.next());
// }
// }
}
}
实体类:
package com.wd.container;
import java.util.GregorianCalendar;
/**
* 创建实体类进行数据存储
*/
public class User implements Comparable<User>{
private int id;
private String name;
private double salary;
private GregorianCalendar entryDate;
public User(int id, String name, double salary, GregorianCalendar entryDate) {
super();
this.id = id;
this.name = name;
this.salary = salary;
this.entryDate = entryDate;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public GregorianCalendar getEntryDate() {
return entryDate;
}
public void setEntryDate(GregorianCalendar entryDate) {
this.entryDate = entryDate;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", salary=" + salary + ", entryDate=" + entryDate + "]";
}
@Override
public int compareTo(User o) {
if(this.entryDate.getTimeInMillis()>o.entryDate.getTimeInMillis()){
return 1;
}else if(this.entryDate.getTimeInMillis()<o.entryDate.getTimeInMillis()){
return -1;
}else{
return 0;
}
}
}