将User对象集合通过城市city加到Map中

有一个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,深圳};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值