考虑如下所示的数组列表
unsortedList = {6,"ball",3,1,"apple","cat",4}
这需要排序
sortedList = {1,"apple",3,4,"ball","cat",6}
按字母顺序对字符串进行排序。按升序排列数字。但要注意以下条件:
- 只要在未排序列表中有一个整数,它就必须是已排序列表中的一个整数。
- 无论在未排序列表中的哪个字符串,它都必须是已排序列表中的一个字符串。
注意上面的例子中,所有的整数都是升序排列的,所有的字符串都是升序排列的,但是整数和字符串的相对位置和之前没有变化。
最佳答案
此处的一个选项是执行以下操作:
- 创建一个包含原始列表中所有整数的新列表。
- 创建一个包含原始列表中所有字符串的新列表。
- 对每个列表进行排序。
- 迭代原始列表,执行以下操作:
- 如果元素有一个整数,从排序的整数列表中写回下一个未写入的整数。
- 如果元素有一个字符串,写回排序后的字符串列表中的下一个未写入的字符串。
这是非常有效的——你只需要做两种排序。这是它的一些代码:
public void relativeOrderSort(List<Object> list) {
/* Create a list of just the integers and just the strings
* from the original list.
*/
List<Integer> intList = new ArrayList<Integer>();
List<String> strList = new ArrayList<String>();
for (Object obj: list) {
if (obj instanceof Integer) {
intList.add((Integer) obj);
} else if (obj instanceof String) {
strList.add((String) obj);
} else {
throw new IllegalArgumentException("List has a non-int, non-string member.");
}
}
/* Sort the lists. */
Collections.sort(intList);
Collections.sort(strList);
/* Merge the lists back together. */
int intIndex = 0, strIndex = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) instanceof Integer) {
list.set(i, intList.get(intIndex++));
} else {
list.set(i, strList.get(strIndex++));
}
}
}
希望这对您有所帮助!
关于java - 对混合整数和字符串的 ArrayList 进行排序,同时保留字符串和整数的相对顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17098477/