有一个User对象集合,需要把集合中的对象将城市相同的放到一个集合中,使用Map,为Map<String,List<User>>。
代码如下:
package test.liuhao.testmap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* 将User对象集合按城市加入Map中
*/
public class TestMap {
public static class User {
Integer id;
String username;
String city;
}
public static void main(String[] args) {
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.id = 001;
user1.username = "Lily";
user1.city = "北京";
userList.add(user1);
User user2 = new User();
user2.id = 002;
user2.username = "sophie";
user2.city = "上海";
userList.add(user2);
User user3 = new User();
user3.id = 003;
user3.username = "Bob";
user3.city = "深圳";
userList.add(user3);
User user4 = new User();
user4.id = 004;
user4.username = "John";
user4.city = "广州";
userList.add(user4);
User user5 = new User();
user5.id = 005;
user5.username = "Krystal";
user5.city = "上海";
userList.add(user5);
User user6 = new User();
user6.id = 006;
user6.username = "Lucy";
user6.city = "北京";
userList.add(user6);
User user7 = new User();
user7.id = 007;
user7.username = "iKun";
user7.city = "北京";
userList.add(user7);
Map<String, List<User>> userMap = new HashMap<String, List<User>>();
userMap = listToMap(userList);
for (Entry<String, List<User>> entry : userMap.entrySet()) {
System.out.print(entry.getKey() + ":");
for (User user : entry.getValue()) {
System.out.print("{" + user.id + "," + user.username + "," + user.city + "};");
}
System.out.println();
}
}
private static Map<String, List<User>> listToMap(List<User> userList) {
Map<String, List<User>> userMap = new HashMap<String, List<User>>();
List<User> tempUsers = new ArrayList<User>();
for (User user : userList) {
String key = user.city;
if (userMap.containsKey(key)) { //若key已在userMap中,则获取该key的集合列表,并添加数据
tempUsers = userMap.get(key);
tempUsers.add(user);
} else {//若key不在userMap中,则new一个新的集合列表添加数据
tempUsers = new ArrayList<User>();
tempUsers.add(user);
}
userMap.put(key, tempUsers);
}
return userMap;
}
}
运行结果如下:
上海:{2,sophie,上海};{5,Krystal,上海};
广州:{4,John,广州};
北京:{1,Lily,北京};{6,Lucy,北京};{7,iKun,北京};
深圳:{3,Bob,深圳};