2015-10-15 44 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); 
相关问题