List中嵌入Map,Map中存对象
首先写一个实体类User.java
package domain;
/**
* @author twc
*
*/
public class User {undefined
private int id;
private String name;
public int getId() {undefined
return id;
}
public void setId(int id) {undefined
this.id = id;
}
public String getName() {undefined
return name;
}
public void setName(String name) {undefined
this.name = name;
}
}
然后写一个ListMapTest.java
ipackage execise;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import domain.User;
/**
* @author twc
*
*/
public class ListMapTest {undefined
/**
* @param args
*/
public static void main(String[] args) {undefined
List<Map<String, Object>> list = test();
for (int i = 0; i < list.size(); i++) {undefined
Map map = list.get(i);
Set set = map.keySet();
Object[] str = set.toArray();
for (int j = 0; j < str.length; j++) {undefined
Object obj = map.get(str[j]);
if (obj instanceof User) {undefined
User user = (User) obj;
System.out.println(user.getName() + "," + user.getId());
map.remove(str[j]);
}
}
}
}
public static List<Map<String, Object>> test() {undefined
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
User user = new User();
user.setId(1);
user.setName("zhangsan");
list.add(add(user, "aa"));
user.setId(2);
user.setName("lisi");
list.add(add(user, "bb"));
return list;
}
public static Map<String, Object> add(User user, String str) {undefined
Map<String, Object> map = new HashMap<String, Object>();
map.put(str, user);
return map;
}
}
看上面是往Map里压入两次,儿值打印出
lisi 2
lisi 2
目前还不清楚 为何 只有打印出lisi来,zhangsna为何打印不出来,
欢迎关注公众号:Java后端技术全栈