我有一个数组列表和一个字符串数组。 String 数组包含 ID,Array List 包含 ID 和与这些 ID 相关的信息。此 ArrayList 的顺序不正确。我有一个 ID 的字符串数组,按照我希望它们在 ArrayList 中的顺序排列。
半伪代码示例:
ArrayList<MyObject> myList = new ArrayList<MyObject>();
for (every username)
{
myList.add(new MyObject(id, username, content, country);
}
String[] ids = new String[myList.size()];
...Ids are added and sorted here...
我现在有一个 ID 列表,顺序正确。 “myList”中的每个 Id 对应于“ids”字符串数组中的一个 Id。我想根据“ids”字符串数组中相应 ID 的顺序对“myList”进行排序。
如何以这种方式重新排序我的 ArrayList?
Eg. if in Array list I have:
1. 123, Bob, test, USA
2. 1234, Vladimir, test, USA
3. 12345, Yoseph, test, USA
and in the String[] I have:
1. 1234
2. 123
3.12345
如何根据字符串数组中的 ID 对 ArrayList 重新排序,从而生成:
1. 1234, Vladimir, test, USA
2. 123, Bob, test, USA
3. 12345, Yoseph, test, USA
最佳答案
一种解决方案是遍历 ids
数组,并在对象中搜索数组中的当前 id
。我们知道它的最终(期望)位置:它是数组中的索引(因为我们希望列表像数组一样排序),所以我们可以将这个元素移动到它在列表中的最终位置(我们通过将它交换为元素位于我们当前在数组中的位置)。
for (int i = ids.length - 1; i > 0; i--) { // Downward for efficiency
final String id = ids[i];
// Big optimization: we don't have to search the full list as the part
// before i is already sorted and object for id can only be on the remaining
for (int j = i; j >= 0; j--) // NOTE: loop starting at i
if (id.equals(myList.get(j).getId()) {
Collections.swap(myList, j, i);
break;
}
}
注意:for
循环省略了最后一个元素 (i==0
),因为如果所有其他元素都已到位,那么最后一个元素也在(它的)位置.
这比创建比较器和使用排序算法(例如 Collections.sort()
所做的)要快得多,因为元素的顺序是已知的(由 定义) ids
数组)和排序算法(无论算法多么聪明)只能使用信息 [less |等于 | greater]
由比较器返回。
关于java - 根据字符串数组的顺序重新排序 ArrayList - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25498874/