1. 程式人生 > >List存放map值不讓其值重複

List存放map值不讓其值重複

錯誤程式碼:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class Test {
	
	public static void main(String[] args) {
		List<User> userList = new ArrayList<User>();
		User user1 = new User();
		user1.setName("張三");
		user1.setAge(15);
		userList.add(user1);
		User user2 = new User();
		user2.setName("李四");
		user2.setAge(25);
		userList.add(user2);
		User user3 = new User();
		user3.setName("王五");
		user3.setAge(35);
		userList.add(user3);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String,Object> map = new HashMap<String, Object>();
		if(null != userList && userList.size() > 0 ){				
			for (User user : userList) {		
				map.put("name", user.getName());
				map.put("age", user.getAge());
				list.add(map);
			}
		}
		System.out.println(list);
	}
}

實體類User:

import java.io.Serializable;
 
public class User implements Serializable{
	private static final long serialVersionUID = 5681523320437838500L;
	
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}

執行結果:

 

[{age=35, name=王五}, {age=35, name=王五}, {age=35, name=王五}]

 

這樣的結果顯示不是我們要的,但問題出現在哪裡呢?

迴圈往list中放入map的時候,一直是同一個map,這樣就會導致後面的資料覆蓋前面的資料,把new HashMap的操作放在for迴圈裡面,修改程式碼為:

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if(null != userList && userList.size() > 0 ){				
			for (User user : userList) {		
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("name", user.getName());
				map.put("age", user.getAge());
				list.add(map);
			}
		}

執行結果:

 

[{age=15, name=張三}, {age=25, name=李四}, {age=35, name=王五}]