有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用java方法按字母顺序组织列表

List <String> cdList = new ArrayList();
Collections.addAll(cdList, "ExampleG","ExampleB","ExampleR","ExampleX");

    bigBox.append("Original Order\n**************\n");

    for (String s : cdList)  {
    bigBox.append(s);
    bigBox.append("\n");
    }

    bigBox.append("\n\nSorted Order\n************\n");

    for (String s : cdList)  {
    bigBox.append(s);
    bigBox.append("\n");
    }

我需要按字母顺序组织列表,并将其显示在“排序顺序”下方,但也需要保留原始顺序,以便在原始订单行下使用


共 (2) 个答案

  1. # 1 楼答案

    你不能将不同的订单保存在同一个列表中

    List <String> cdList = new ArrayList<String>();
    Collections.addAll(cdList, "ExampleG","ExampleB","ExampleR","ExampleX");
    
    
    List<String> sortedList = new ArrayList<String>(cdList);
    Collections.sort(sortedList);
    

    如果适用,我强烈建议您使用泛型

  2. # 2 楼答案

    原始清单:

    // leave this variable untouched
    List<String> cdList = Arrays.asList("ExampleG","ExampleB","ExampleR","ExampleX");
    

    已排序列表:

    List<String> sorted = new ArrayList<String>(cdList);
    Collections.sort(sorted);  // "sorted" is the sorted list
    

    现在您可以迭代cdListsorted,并将它们附加到bigBox

    bigBox.append("Original Order\n**************\n");
    for (String s : cdList) {
        bigBox.append(s);
        bigBox.append("\n");
    }
    bigBox.append("\n\nSorted Order\n************\n");
    for (String s : sorted) {
        bigBox.append(s);
        bigBox.append("\n");
    }
    

    好了