我有一个包含多个分类行的文件。 现在我想将所有这些行排序到一个新文件中的一个合并行中。不需要一次加载所有数字。从.txt文件中获取合并行
这是我的文件的一部分:
12,86,280,304,350,359,371,391,405,548,
255,264,325,346,435,466,483,
39,114,214,298,317,377,428,438,575,
35,165,183,281,336,367,386,418,438,593,
44,77,97,117,122,156,251,415,533,
109,155,163,172,212,226,340,358,452,577,592,
33,74,91,204,256,307,357,388,534,552,554,570,
50,99,246,309,345,358,395,405,419,425,566,
现在我想这些排序合并,所以起初我需要知道文件多少行了。然后我需要获取所有的第一个元素并进行比较。我写入新文件的最低。然后,我必须从我刚刚写下的行中得到第二个数字。并将它们与其他行的第一个数字进行比较。我该怎么做呢。我写了一个归并为的ArrayList:
//as long as there is unsorted data
while (listOfOutputs.size() > 0) {
//Set the lowest undefined
List<Integer> lowest = null;
for (List<Integer> list : listOfOutputs) {
//if the lowest is undefined, I'm the lowest
if (lowest == null) {
lowest = list;
//Else am I lower then the lowest? Then I'm the lowest
} else if (list.get(0) < lowest.get(0)) {
lowest = list;
}
}
//Finally the lowest is added to the sorted list and removed to from his own list.
assert lowest != null;
sortedList.add(lowest.remove(0));
//Is the size of the list which contained to lowest now 0, remove him from the listOfOutputs
if (lowest.size() == 0) listOfOutputs.remove(lowest);
}
但我不知道怎么改写成一个排序我的文件这一点。我如何做到这一点,而无需将它们加载到列表中。
斯文
简单地阅读每一行,在读取时解析每一行并将每个已解析的整数附加到一个列表中,最后一次对整个列表进行排序是否可行? – jarmod
您的数据是否太大而无法放入内存?这就是为什么你不想只将所有数据加载到一个数组中并对其进行排序的原因? –