我在获取两个对象列表并将它们有效地连接在一起以本质上创建在我的 api 端点上返回的第三个数据模型时遇到问题。问题之一是我从一个数据库获取实体 [Employees] 列表,然后从另一个数据库获取另一个实体 [ClockedIn] 列表,因此它看起来像这样:
class Employee {
private Integer employeeID;
private String firstName;
private String lastName;
etc...
//corresponding getters and setters
}
和
class ClockedIn {
private Integer employeeID;
private Date timeStamp;
etc...
//corresponding getters and setters
}
现在加入,我这样做:
List<Employee> getEmployees = repository.getAll();
List<ClockedIn> getClockedIn = repository.getAll();
List<JoinedDataModel> joinedDataModelList = new ArrayList<JoinedDataModel>();
for(Employee emp : getEmployees) {
JoinedDataModel joinDataModel = new JoinedDataModel();
int currentId = empt.getEmployeeId();
List<Dates> missingClockedIn = new ArrayList<Dates>();
for(ClockedIn ci : getClockedIn) {
if(currentId == ci.getEmployeeId) {
// add together to the third datamodel
joinDataModel.setId();
if(missingDate(ci.getTimeStamp()) {
missingClockedIn.add(ci.getTimeStamp());
}
}
joinDataModel.setMissingClockedIn(missingClockedIn);
}
}
joinedDataModelList.add(joinDataModel);
我在 ClockedIn 列表中有大约 70k 个项目,在 Employee-List 中有 1400 个项目,计算大约需要 15 秒,但应该考虑到我需要从两个不同的数据库检索数据。 但是,如果我将 10k 添加到 ClockedIn 列表中,服务器就会超时,我对 Big O 表示法不太了解,但我认为我现在设置它的方式性能相当沉重,因为我认为它是嵌套循环O(n2)?
我可以采取更有效的方法吗?我认为会让事情变得更顺利的一件事是,如果在映射到第三个数据模型之前将两个列表连接在一起,但我对如何以更优雅的方式做到这一点感到困惑。
对我上述实现的任何意见将不胜感激!
谢谢!
*免责声明,所有内容都是伪代码,因此此处发布的代码中发现的任何语法错误或类似内容与我的问题无关。
最佳答案
基本思想是,您将运行 ClockedIn 集合并将它们组织到 ArrayList 中,可以使用 EmployeeId 值轻松访问该 ArrayList。这是使用 HashMap 对象完成的,该对象可以使用 EmployeeId 作为快速访问的键。示例:
//Class declaration for example use
class Employee {
int employeeId;
//Plus any other info
Employee(int employeeId) {
this.employeeId = employeeId;
}
}
class ClockedIn{
int employeeId;
//Plus any other info
ClockedIn(int employeeId) {
this.employeeId = employeeId;
}
}
//Data creation for example use
private List<Employee> getEmployeeData() {
List<Employee> data = new ArrayList<>();
for(int i = 0; i < 50; i++) {
data.add(new Employee(i));
}
return data;
}
private List<ClockedIn> getClockedInData() {
List<ClockedIn> data = new ArrayList<>();
for(int i = 0; i < 1000; i++) {
data.add(new ClockedIn(i % 50));
}
return data;
}
//Actual hashmapping and combining
private void hashmap() {
HashMap<Integer, ArrayList<ClockedIn>> map = new HashMap<>();
for(ClockedIn data : getClockedInData()) {
if(map.get(data.employeeId) == null)
map.put(data.employeeId, new ArrayList<ClockedIn>());
map.get(data.employeeId).add(data);
}
for(Employee data : getEmployeeData()) {
ArrayList<ClockedIn> relatedClockData = map.get(data.employeeId);
//Combine the Employee data with the related ClockedIn data here
}
}
关于java - 如何在 Java 7 中有效地连接 id 上的两个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60442927/