2015-10-15 39 views
1

我有兩個數組列表list1list2,我想list2順序爲list1的順序。有沒有辦法做到這一點?在一個清單中,我從數據庫中獲得了最高績效的僱員,第二個清單從數據庫第二次使用"in"條款中的最高績效員工ID進行了分析。我們可以基於其他來製作一個列表的順序嗎?


List<Long> list1 = new ArrayList<Long>(); 
list1.add(5645); 
list1.add(2312); 
list1.add(7845); 
list1.add(1212); 

和對象類型的其它表:

List<Employee> list2 = new ArrayList<Employee>(); 
list2.add(new Employee(1212, "A")); 
list2.add(new Employee(2312, "V")); 
list2.add(new Employee(5645, "D")); 
list2.add(new Employee(7845, "T")); 

其中list1示出的頂部4的僱員ID;

我使用id從數據庫中獲得員工詳細信息並獲得了此列表2。

現在我想讓list2的訂單爲list1顯示在html頁面上。

+0

yes有辦法做到這一點,你有沒有試過你的東西自我呢? – SomeJavaGuy

回答

0
List<Long> list1 = new ArrayList<Long>(); 
list1.add(5645); 
list1.add(2312); 
list1.add(7845); 
list1.add(1212); 

和對象類型的其他列表:

List<Employee> list2 = new ArrayList<Employee>(); 
list2.add(new Employee(1212, "A")); 
list2.add(new Employee(2312, "V")); 
list2.add(new Employee(5645, "D")); 
list2.add(new Employee(7845, "T"));  

    Collections.sort(list1, new Comparator<Long>() { 

     @Override 
     public int compare(Parameter) { 
      //Add your logic here for sorting 
     } 

    }); 
    // now sort the list B according to the changes made with the order of 
    // items in list1 
    Collections.sort(list2, new Comparator<Employee>() { 

     @Override 
     public int compare(Parameter) { 
      //    your logic for sorting. 
     } 

    }); 

可能是這個鏈接可以幫助您:In Java how do you sort one list based on another?

0

只是想迭代list1併爲每個項目找到匹配的元素list2。無需排序。

List<Employee> sortedList = new ArrayList<>(); 
for (Long id : list1) { 
    Employee match = CollectionUtils.find(list2, e -> e.id.equals(id)); 
    // cannot sort, if list2 does not contain the id, or put your rule for this case 
    assert match != null; 
    sortedList.add(match); 
} 

這使用Apache Commons Collections的CollectionUtils

或者,更好的性能,打造Map第一:

Map<Long, Employee> lookupMap = new HashMap<>(list2.size()); 
for (Employee e : list2) 
    lookupMap.put(e.id, e); 

List<Employee> sortedList = new ArrayList<>(list2.size()); 
for (Long id : list1) 
    sortedList.add(lookupMap.get(id)); 
+0

是的,我是用地圖做的,但我只想通過列表來做到這一點 –

+0

有兩種解決方案在這裏:有和沒有地圖,請看第一個。 – Oliv

0

你應該做的是讓數據庫命令的結果:

SELECT name, score FROM Employees 
    ORDER BY score DESC 
    LIMIT 4; 

如果你堅持在Java中的排序,使用自定義Comparator

List<Long> top = Arrays.asList(5645L, 2312L, 7845L, 1212L); 
List<Employee> employees = Arrays.asList(
     new Employee(1212, "A"), 
     new Employee(2312, "V"), 
     new Employee(5645, "D"), 
     new Employee(7845, "T") 
); 

Comparator<Employee> indexOf = (o1, o2) -> top.indexOf(o1.id) - top.indexOf(o2.id); 
Collections.sort(employees, indexOf); 
相關問題