public class MyTest {
class User{
String name;
int age;
public User(String name,int age) {
this.name = name;
this.age = age;
}
}
public static void main(String[] args) {
MyTest myTest = new MyTest();
List users = new ArrayList();
User user1 = myTest.new User("zhangsan", 18);
User user2 = myTest.new User("lisi", 18);
User user3 = myTest.new User("wangwu", 18);
User user4 = myTest.new User("zhangsan", 19);
User user5 = myTest.new User("zhangsan", 20);
User user6 = myTest.new User("lisi", 19);
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
users.add(user6);
/*根据name将user放到不同新的的list*/
Map map = new HashMap>();
for (User user : users){
//如果map中不存此name,则以此name为key
if(map.get(user.name) == null ){
List list = new ArrayList();
list.add(user);
map.put(user.name,list);
}else{
List list = (List) map.get(user.name);
list.add(user);
map.put(user.name,list);
}
}
List zhangsans = (List)map.get("zhangsan");
for (User user : zhangsans){
System.out.println(user.name+" : "+user.age);
}
System.out.println(map.get("zhangsan"));
}
}
直接写点代码了`