3 回答

TA貢獻1946條經(jīng)驗 獲得超4個贊
雖然一般來說我不贊成使用Map用于保存對象的字段,但如果屬性的數(shù)量很大,甚至可能因 CSV 文件而異(例如,某些文件有一個人就讀的大學(xué),另一個沒有),那么使用 aMap來保存屬性可能是合適的。
在這種情況下,可以定義一個簡單的Person類:
public class Person {
Map<String, String> props = new HashMap<>();
public void addProperty(String propertyName, String value) {
// could add error checking to ensure propertyName not null/emtpy
props.put(propertyName, value);
}
/**
* returns the value of the property; may return null
*/
public String getProperty(String propertyName) {
return props.get(propertyName);
}
}
如果知道將始終加載某些屬性/屬性,則getName()可以添加諸如此類的訪問器:
public String getName() {
return props.get("name");
}
public int getAge() {
String age = props.get("age");
// or throw exception if missing
return (age != null ? Integer.parseInt(age) : -1);
}
盡管請注意,對于大多數(shù)數(shù)據(jù)集,我希望 name 不是單個條目,因為通常會有姓氏、名字等。 盡管如此,有限數(shù)量的常見預(yù)期值的模式是相同的。此外,您可以進行調(diào)整,以便您可以直接獲取某些知名字段的整數(shù)值。
然后,在解析文件時,保留具有屬性定義的標(biāo)題行。然后,對于隨后讀取的每一行,創(chuàng)建一個新Person對象,然后按順序添加屬性。
List<Person> allPersons = new ArrayList<>();
while ( (line = READ_NEXT_LINE) ) {
// NOTE: this is not a safe way to handle CSV files; should really
// use a CSV reader as fields could have embedded commas
attrs[] = line.split(",");
Person p = new Person();
for (int i = 0; i < titleRow.length; ++i) {
p.addProperty(titleRow[i], attrs[i]);
}
allPersons.add(p);
}
然后你可以得到一個特定Person的Person myPerson = allPersons.get(index_of_person),和你使用的方式非常相似Javascript,你可以做String val = myPerson.getProperty("age")。
如果您需要按給定的屬性進行搜索,則可以allPersons根據(jù)給定的屬性對等價性進行流/循環(huán)和檢查。
// find all people of a given age
List<Person> peopleAge20 = allPersons.stream()
.filter(p -> p.getAge() == 20)
.collect(Collectors.toList());
System.out.println(peopleAge20);
// summary statics (average age) for all people
IntSummaryStatistics stats =
allPersons.stream().mapToInt(p -> p.getAge()).summaryStatistics();
System.out.printf("Average age: %f\n", stats.getAverage());
請注意,這種方法確實打破了 a 的想法Javabean,但這可能是也可能不是問題,具體取決于您的要求。
添加回答
舉報