2011-04-05 86 views
1

通过我有一个函数返回的对象的列表,其ID是一个给定的阵列中:订单查询结果作为参数

public static List<T> findByIds(int[] ids) {   
    final String where = "_ID IN (" + StringUtils.implode(ids, ",") + ")"; 
    final Cursor c = db.query(TABLE, ALL_COLUMNS, where, null, null, null, null); 

    final List<T> result = new ArrayList<T>(c.getCount()); 
    while (c.moveToNext()) { 
     final T t = createFromCursor(c); 
     result.add(t); 
    } 
    c.close(); 

    return result; 
} 

我需要的结果是在相同的顺序ids函数参数。 ids功能参数最多有200到300个元素。

我看了一下Ordering query result by list of values这似乎解决了同样的问题,但答案中有很多SQLServer特定的东西。

对于基于SQL(获得结果排序)或Java(后续命令)解决方案的任何建议?

回答

0

如果列表足够短,您可以随时手动对结果进行排序:根据排序顺序作为关键字构建地图,然后根据排序顺序构建新列表。这不是高效,我会说,但效率不如运行代码重要。这里有一个例子:

package sorting; 

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

public class SortResult { 

public static void main(String[] args) { 
    int[] sortOrder = { 5, 2, 8, 4, 14, 1, 6, 9, 3, 7 }; 
    List<Thing> things = new ArrayList<Thing>(); 
    for (int i = 1; i < 10; i++) { 
     Thing thing = new Thing(); 
     thing.setId(i); 
     things.add(thing); 
    } 
    Map<Integer, Thing> thingMap = new HashMap<Integer, Thing>(); 
    for (Thing thing : things) { 
     thingMap.put(thing.getId(), thing); 
    } 
    List<Thing> sortedThings = new ArrayList<Thing>(); 
    for (int id : sortOrder) { 
     if (thingMap.get(id) != null) { 
      sortedThings.add(thingMap.get(id)); 
     } 
    } 
    System.out.println("expected order: "+Arrays.toString(sortOrder) 
       +"\nActual order: "); 
    for(Thing thing:sortedThings) { 
     System.out.println(thing); 
    } 
} 
} 

class Thing { 
int id; 

public int getId() { 
    return id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

@Override 
public String toString() { 
    StringBuilder builder = new StringBuilder(); 
    builder.append("Thing [id=").append(id).append("]"); 
    return builder.toString(); 
} 
} 
+0

这就是我会使用,直到我有一些时间(和需要)来优化该功能。感谢您的意见。 – 2011-04-05 13:23:44

2

使用

java.util.Collections.sort(List<T> list, Comparator<? super T> c) 

通过你的IDS的比较,并用一件T做排序的它的位置。

+0

由于我的ID阵列是没有排序,我认为这将是比一个HashMap中查找一些效率较低,即使是更高效的内存明智的。无论如何感谢您的建议。 – 2011-04-05 13:25:17