通过用户选择选择随机选项,语言选项的显示应按列表中显示的顺序显示?

时间:2013-09-20 11:26:59

标签: java alphabetical-sort

请有人帮助我克服这个问题。问题。问题陈述是:

由于某些复选框,我写了一些用于显示网页用户选择语言的代码。假设用户为德语和乌尔都语选择两个复选框,然后我需要在网页上显示德语,乌尔都语。然后用户再次选择另一个语言选项,如阿拉伯语,然后我需要在阿拉伯语,德语,乌尔都语等网页上显示。

谢谢高级。

   knownLanguages ="German,Urdu,Arabic";  
   String userLanguages[] = knownLanguages.split(",");
    for (int i = 0; i < userLanguages.length; i++) {
      if (i == 0)
        knownLanguages1 += userLanguages[i];
      else
        knownLanguages1 += " , " + userLanguages[i];
    }
    List<String> list = new ArrayList<String>(Arrays.asList(knownLanguages1.split(" , ")));
    Collections.sort(list, ALPHABETICAL_ORDER);
    return knownLanguages1;
  }

  private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
      int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
      if (res == 0) {
        res = str1.compareTo(str2);
      }
      return res;
    }
  }; 

但是这段代码没有给出理想的输出。请帮助我。

2 个答案:

答案 0 :(得分:2)

您不需要自定义比较器,因为您所做的只是alphabetical sorting

以下代码应该适合您:

String knownLanguages ="German,Urdu,Arabic";
// get a list of languages from above string using String#split
List<String> langList = Arrays.asList(knownLanguages.split(","));
// sort the resulting list
Collections.sort(langList);
// print it
System.out.println(langList);
// OUTPUT: [Arabic, German, Urdu]

答案 1 :(得分:0)

   private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
         public int compare(String str1, String str2) {         
             return  str1.compareToIgnoreCase(str2);;
         }      
   };