出于您的目的,听起来您确实想要一个对象来代表一个具有一定经验的人。由于您的输入源对数据进行了非规范化,因此最简单的方法是在解析文件时填充 Map<String,Person>:
scanner.useDelimiter(",|\\n");
while (scanner.hasNext()) {
String line = scanner.next();
String[] fields = line.split(",");
String name = fields[0];
Person person = map.get(name);
if (person == null) {
person = new Person(name);
map.put(name, person);
}
person.addJob(fields[1], Integer.parseInt(fields[2]));
}
List<Person> people = new ArrayList<Person>(map.values());
在此过程之后,您最终会得到一份人员列表,没有特定的顺序。对于每个人,由于您希望按经验对他们的工作进行排序,因此您需要以使其保持有序的方式实现Person.addJob。 SortedSet 是一种非常好的方法,但是您不能插入重复项,并且由于您想按经验排序,并且一个人可能在两份工作中花费相同的时间需要使用替代方法。有几种方法可以做到这一点,但在不对您的数据做出假设的情况下,我建议保留 List 的 Job 对象的排序:
class Person {
private final List<Job> jobs = new LinkedList<Job>();
// Constructor, etc...
public void addJob(String companyName, int yearsOfExperience) {
Job newJob = new Job(companyName, yearsOfExperience);
int insertionIndex = Collections.binarySearch(jobs, newJob);
if (insertionIndex < 0) {
insertionIndex = (-(insertionIndex) - 1);
}
jobs.add(insertionIndex, newJob);
}
}
最后,Job 应该实现Comparable<Job>,这样你就可以查找它:
class Job implements Comparable<Job> {
private final String companyName;
private final int yearsOfExperience;
// Constructor, etc...
public int compareTo(Job otherJob) {
return Integer.compare(yearsOfExperience,otherJob.yearsOfExperience);
}
}
Person.addJob 中的那一点诡计将使 List 始终按 Job 的 'natural order' 排序。 (见Collections.binarySearch)。