Heim > Fragen und Antworten > Hauptteil
请问java 结果集list<user>,根据user.name属性,如何再将结果集中的name属性相同的user放到一个新的list中?user的name可能多个,不固定,根据name将user放到不同新的的list
三叔2016-11-05 13:14:54
直接写点代码了`
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(); Listusers = 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")); } }