如何对包含数字和特殊字符的字母列表进行排序?

时间:2019-04-03 06:38:09

标签: java sorting collections io

我的问题实际上是双重的,但是首先,我试图编写一个程序,该程序按字母顺序对列表进行排序并将其写入文件,但是当尝试对文件进行排序时,使用特殊字符或数字的行被引入后,排序将不再起作用。如果列表只是以字母开头的字符串,则可以按顺序很好地进行排序和书写。

我只是在由输入文件中的行组成的字符串列表中使用Collections.sort,然后尝试将它们写入输出文件。

我的输入文件包含以下几行:

These are some test lines
short line
abcdefghij
this line is much longer than the short line
123 456
#Ignore this line
Blah blah blah
# ignore this, too

我的输出文件最终被排序为:

# ignore this, too
#Ignore this line
123 456
Blah blah blah
These are some test lines
abcdefghij
short line
this line is much longer than the short line

对于第二个问题,我想以某种方式排除将#所包含的行写入文件。 这是我的代码:

BufferedReader inputStream = null;
        PrintWriter outputStream = null;
        String inFile = args[0];
        String outFile = args[1];
        List<String> lines = new LinkedList<>();

        try {
            inputStream =
                    new BufferedReader(new FileReader(inFile));
            outputStream=
                    new PrintWriter(new FileWriter(outFile));
            String line;
            while ((line = inputStream.readLine()) != null) {
                lines.add(line);
                if(args[2].equals("LONGESTFIRST") ) {
                    Collections.sort(lines, new Comparator<String>() {
                        @Override
                        public int compare(String o1, String o2) {
                            return o2.length() - o1.length();
                        }
                    });
                } else if (args[2].equals("SHORTESTFIRST")) {
                    Collections.sort(lines, new Comparator<String>() {
                        @Override
                        public int compare(String o1, String o2) {
                            return o1.length() - o2.length();
                        }
                    });
                } else if (args[2].equals("LEXICOGRAPHIC")) {
                    Collections.sort(lines);
                } else if (args[2].equals("REVERSE")) {
                    Collections.sort(lines, Collections.reverseOrder());
                }
            }
            for (int i = 0; i < lines.size(); i++) {
                outputStream.println(lines.get(i));
            }

我已经尝试过在诸如if(!lines.startsWith("#") {之类的if语句中包括倒数第二行的操作,但是不幸的是,这行不通。

对不起,文字墙!

2 个答案:

答案 0 :(得分:0)

第一件事是:您不必在每次插入后将列表排序。

第二个是:如果您不希望在输出中出现带有#个字符的行,则只需使用list.get(i).contains("#")进行检查。如果返回true,请从列表中删除该行。

所以最终的算法可能看起来像这样:

  1. 从文件中读取行,将每一行添加到列表中。
  2. 使用您的比较器之一(仅一次)对列表进行排序,与您目前使用的方法相同。
  3. 遍历列表。检查一行是否可以有效写入文件(list.get(i).contains("#")或您喜欢的任何内容),如果有效,请将其写入文件。


 更新
对于不区分大小写的排序,您可能要使用CASE_INSENSITIVE_ORDER类提供的默认比较器String

List<String> myList = ...;
Collections.sort(myList, String.CASE_INSENSITIVE_ORDER);

答案 1 :(得分:0)

您不必在列表中放置此类行

while ((line = inputStream.readLine()) != null) {
  if (line.startsWith("#"))
    continue;
  lines.add(line);
  // ...
}
相关问题