我认为最好有一个 Person 类并在每一行中实例化它(带有年龄和名称)。还有一个用于读取文件和搜索的 PersonCatalog 类:
public class PersonCatalog
{
private List<Person> persons = new ArrayList<Person>();
public void readFile(String filePath) throws NumberFormatException, IOException
{
BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));
String currentLine;
int index = 0;
while((currentLine = reader.readLine()) != null)
{
String[] pair = currentLine.split(",");
if(index != 0)
{
persons.add(new Person(pair[1].trim(),Integer.valueOf(pair[0].trim())));
}
index++;
}
reader.close();
}
public List<Person> searchByAge(int age)
{
List<Person> results = new ArrayList<Person>();
for(Person p : persons)
{
if(p.getAge() == age)
{
results.add(p);
}
}
return results;
}
public static void main(String[] args) throws IOException
{
PersonCatalog personCatalog = new PersonCatalog();
personCatalog.readFile("G:/test.csv");
List<Person> persons = personCatalog.searchByAge(30);
for(Person person : persons)
{
System.out.println(person.getName() + " " + person.getAge());
}
}
}
public class Person
{
private String name;
private Integer age;
public Person(String name, Integer age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public Integer getAge()
{
return age;
}
}
输入:
age, name
11, sam
15, jack
3, nani
30, david
输出:
david 30