2015-11-24 14 views
0

Java對象有一個對象是這樣的最好的方法組由多個字段

public class Person { 

private String id;  
private String firstName; 
private String lastName; 
private Float weight; 
private Date birthday; 
private String address; 
..... 

需要由5個字段(名字,姓氏,體重,生日,地址),其結果一羣人名單地圖

Map<String, List<Person>> groupedPersons = ... 

有一個解決方案這樣的番石榴等:

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Equivalence.html

還有其他(更好的)方法嗎?

+0

按照不同的鍵分組的條目有什麼意義?我只能看到一個解決方案 - 按每個字段分組,然後將所有地圖聯合起來。 – k0ner

回答

0

我會用的hashCode()方法:

@Override 
public int hashCode() { 
    int result = id != null ? id.hashCode() : 0; 
    result = 31 * result + (firstName != null ? firstName.hashCode() : 0); 
    result = 31 * result + (lastName != null ? lastName.hashCode() : 0); 
    result = 31 * result + (weight != null ? weight.hashCode() : 0); 
    result = 31 * result + (birthday != null ? birthday.hashCode() : 0); 
    result = 31 * result + (address != null ? address.hashCode() : 0); 
    return result; 
} 

然後使用地圖:HashMap中> groupPersons ...

+1

'Objects.hash(id,firstName,lastName,weight,birthday,address)'會更容易。 –

+0

這是正確的,謝謝。 –

0

有兩種方法,一個類需要重寫,以使該對象類工作哈希映射鍵:

public int hashCode(); 
public boolean equals(Object o); 

然後,您可以使用HashMap來區分組值。
如果地圖先前包含密鑰的映射,則舊值將替換爲HashMap.put(K key, V value)

Eclipse可以自動生成並自動覆蓋API。