在 java 中使用 RuleBasedCollat​​or 设置排序规则面临困难

我正在尝试执行以下自动化操作:

  1. 从已经升序的网页中获取字符串值列表。

  2. 我想确保网页给定的值升序是否正确。

  3. 所以我将值存储在从网页收集的数组中。

  4. 从网页收集值后,我对该数组进行排序,但是在使用 java 代码排序后,我看不到相同的值以升序排列。

这些是我从网站上升后得到的值:

_john

_tim

11

111

5

A

aaa

aaa

AI-1

Android

API

AppName

asd

AWS

AWS

awstest

AWSTest1type

Azure

在使用 java 集合进行排序后,我得到如下所示:


 _john

    _tim

    11

    111

    5

    A

   AI-1

   API

   AWS

   AWS

  Android

  AppName

  Azure

  aaa

  aaa

我用来排序的代码:


String rules = "< '_' < 1 < 2 <3 <4 < 5 < A < a";

        Collections.sort(myStringArray, new RuleBasedCollator(rules));

我可以遗漏上述规则中的任何内容吗?


陪伴而非守候
浏览 213回答 1
1回答

互换的青春

这是由于 ASCII 字符集的顺序,其中 'Z' 先于 'a'RuleBasedCollator 仅检查要排序的字符串的第一个字母。正如您设定的规则是(A < a)。它首先列出所有以大写字母开头的字符串,然后是小写字母。由于您的列表包含以特殊字符开头的字符串,我建议创建两个列表进行排序。一个用于以特殊字符开头的字符串,然后是包含所有其他值的其他列表。分别对这两个列表进行排序,然后合并排序后的列表。我已经尝试了下面的代码,它工作正常// Input listList<String> name = new ArrayList<String>();&nbsp; &nbsp; final String[] specialChars = { "_", ">" };&nbsp;&nbsp; &nbsp; List<String> specCharList = new ArrayList<String>();&nbsp; &nbsp; List<String> strList = new ArrayList<String>();&nbsp; &nbsp; List<String> finalList = new ArrayList<String>();&nbsp; &nbsp; String rules = "< '_' < '>' ";&nbsp; &nbsp; boolean isSpec = false ;&nbsp; &nbsp; for(String names : name) {&nbsp; &nbsp; &nbsp; &nbsp; isSpec = false ;&nbsp; &nbsp; &nbsp; &nbsp; for(int i=0;i<specialChars.length;i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(names.startsWith(specialChars[i])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // System.out.println("Name : "+names);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isSpec = true ;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; // to sort special char list and normal list&nbsp; &nbsp; &nbsp; &nbsp;if(isSpec) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;specCharList.add(names);&nbsp; &nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;strList.add(names);&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; }&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; // To sort special character list&nbsp; &nbsp; &nbsp; &nbsp; Collections.sort(specCharList, new RuleBasedCollator(rules));&nbsp; &nbsp; &nbsp; &nbsp; // Add the sorted list to finallist&nbsp; &nbsp; &nbsp; &nbsp; finalList.addAll(specCharList);&nbsp; &nbsp; &nbsp; &nbsp; // to sort other list&nbsp; &nbsp; &nbsp; &nbsp; Collections.sort(strList, String.CASE_INSENSITIVE_ORDER);&nbsp; &nbsp; &nbsp; &nbsp; // Add the sorted list to finallist&nbsp; &nbsp; &nbsp; &nbsp; finalList.addAll(strList);&nbsp; &nbsp; } catch (ParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated catch block&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("Final Output List --------");&nbsp; &nbsp; for(String names : finalList) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(names);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java