1. 程式人生 > >List合併具有相同屬性的物件

List合併具有相同屬性的物件

業務背景:一個list集合了若干個student物件,並且student物件具有name和money屬性,此時我們需要合併具有相同name屬性的student的money.

Student類的程式碼:

public class Student {
	private String name;
	private int money;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getMoney() {
		return money;
	}
	public void setMoney(int money) {
		this.money = money;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + money;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		//將money屬性註釋,則物件的equals()方法會忽略money屬性的比較
//		if (money != other.money)
//			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", money=" + money + "]";
	}
	
}

建立我們的list:
<span style="white-space:pre">		</span>Student s1 = new Student();
		s1.setName("peter");
		s1.setMoney(10);
		Student s2 = new Student();
		s2.setName("peter");
		s2.setMoney(20);
		Student s3 = new Student();
		s3.setName("jack");
		s3.setMoney(5);
		Student s4 = new Student();
		s4.setName("jack");
		s4.setMoney(15);
		List<Student> list = new ArrayList<Student>();
		list.add(s1);
		list.add(s2);
		list.add(s3);
		list.add(s4);

第一種合併方式:
<span style="white-space:pre">		</span>for ( int i = 0 ; i < list.size() - 1 ; i ++ ) {
			for (int j = list.size() - 1 ; j > i; j --) {
				Student stu = list.get(i);
				Student otherStu = list.get(j);
				if(stu.equals(otherStu)) {
					int money = stu.getMoney();
					int otherMoney = otherStu.getMoney();
					int totalMoney = money + otherMoney;
					stu.setMoney(totalMoney);
					list.remove(j);  
				}
			}
		}

<span style="white-space:pre">		</span>for (Student student : list) {
			System.out.println(student.toString());
		}

結果如下:
Student [name=jack, money=20]
Student [name=peter, money=30]

第二種合併方式:
<span style="white-space:pre">		</span>Map<String, Student> map = new HashMap<String, Student>();  
		for (Student student : list) {
			String key = student.getName();
			if(map.containsKey(key)) {
				Student stu = map.get(key);
				int preMoney = stu.getMoney();
				int total = preMoney + student.getMoney();
				student.setMoney(total);
			} 
			map.put(key, student);
		}
		
		list.clear();
		list.addAll(map.values());
		
		for (Student student : list) {
			System.out.println(student.toString());
		}

結果與上面一致.

總結:個人認為第二種方式更加清晰,更加容易理解,建議採用第二種方式.