簡體   English   中英

Java從對象列表中獲取子列表

[英]java get sub list from a list of objects

有一個依賴清單

家屬包含

String emp_Id, name etc,

List<Dependent> dependentList;

dependentList包含員工的所有相關信息。

如何通過提供emp_Id獲得受撫養者列表?

例如,一個雇員將有2或3個家屬。

好吧,我不想循環。

我嘗試使用比較器對列表進行二進制搜索,但未返回所需數據。

我已經遍歷了員工列表...隨后我應該獲得特定員工的依賴...什么是最佳和高效的解決方案?

僅當根據比較器對列表進行排序時,二進制搜索才有效。 對於未按其他標准排序或未排序的列表,必須對其進行過濾。

  • 循環遍歷列表,然后在循環正文中執行您想做的任何事情
  • 或使用庫中的過濾器功能

如果您要過濾,則建議使用Google Collections (或Google Guava ,它是Google Collections的超集):

Collection<Dependent> filtered = Collections2.filter(dependentList, new Predicate<Dependent>() {
  public boolean apply(Dependent from) {
    return from != null && from.getId().equals(id_so_search_for);
  }
}

當然,您不限於.equals() ,而是可以根據所需的任何操作進行匹配(例如,通過正則表達式)。

如果搜索一種類型的數據非常重要,而搜索其他任何類型的數據,則將它們存儲在Map<kind-of-id, Dependent>也是一個不錯的選擇。 您仍然可以使用Map.values()檢索所有存儲對象的集合。

如果一個鍵映射到多個項目,請使用Map<kind-of-id, Collection<Dependent>>或(最好)考慮使用現有的Multimap功能: com.google.common.collect.Multimaporg.apache.commons .collections.MultiMap (請注意,Apache Commons沒有通用版本)。

您想建立關系模型。 我想,您具有基本的依賴關系:

  • 主管雇員
  • 主管有很多員工(您的情況取決於家屬)

因此,一個非常基本的實現可以像這樣:

public class Employee {
  int emp_id;
  // more fields, more methods
}

public class Supervisor extends Employee {
  private List<Employee> dependants = new ArrayList<Employee>();
  // more fields, more methods

  public List<Employee> getDependants() {
   return dependants;
  }
}

public class StaffDirectory {
  private Map<Integer, Employee> staff = new HashMap<Integer, Employee>();

  public static List<Employee> getAllDependantsOf(int employeeId) {
    Employee employee = staff.get(employeeId);
    if (employee instanceof Supervisor) {
      return ((Supervisor) employee).getDependants());
    } else {
      return Collections.emptyList();
    }
  }
} 

你試過什么了? 你有寫東西嗎?

這是一個一般的猜測:

 int employeeToFind = 10;//the id to search for
for(Dependant dep : dependentList ) {

    if(dep.getEmployeeId() == employeeToFind) {

        //do something
    }


}

您也可以將依賴項存儲在Hashtable<Integer employeeId,List<Dependent>>(); 由EmployeeId鍵控,以便於查找。

正如alzoid所述,HashMap或HashTable是完成此任務的理想數據結構。 如果您有機會將Dependent實例加載到此類對象中,請這樣做。 仍然,有這個美味的代碼:

String emp_Id //IDs are usually integer, but I'll go with your example
List<Dependent> dependentList; //assume this is populated
List<Dependent> desiredSublist = new ArrayList<Dependent>();
for(Dependent dep:dependentList){
   //make sure to compare with equals in case of Id being String or Integer
   if(dep.getId().equals(emp_Id)){
      desiredSubList.add(dep);
   }
}
//desiredSublist now contains all instances of Dependent that belong to emp_Id.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM