【问题标题】:sorting arraylist of string in android [duplicate]在android中对字符串的arraylist进行排序[重复]
【发布时间】:2011-08-14 11:26:54
【问题描述】:

我有一个字符串数组列表'names'。其中包含人名。我想按字母顺序对数组列表进行排序。请帮助我

【问题讨论】:

    标签: java android


    【解决方案1】:

    这会解决你的问题...

    ArrayList arrayList = new ArrayList();
    
    //Add elements to Arraylist
    arrayList.add("1");
    arrayList.add("3");
    arrayList.add("5");
    arrayList.add("2");
    arrayList.add("4");
    
    
    Collections.sort(arrayList);
    
    //display elements of ArrayList
    System.out.println("ArrayList elements after sorting in ascending order : ");
    for(int i=0; i<arrayList.size(); i++)
        System.out.println(arrayList.get(i));
    

    要对 ArrayList 对象进行排序,请使用 Collection.sort 方法。这是一个 静态方法。它将 ArrayList 对象的元素按升序排序。


    以防万一下面的注释中的代码不起作用意味着... 试试这个代码..

    创建自定义比较器类:

    import java.util.Comparator;
    
    class IgnoreCaseComparator implements Comparator<String> {
      public int compare(String strA, String strB) {
        return strA.compareToIgnoreCase(strB);
      }
    }
    

    然后按你的排序:

    IgnoreCaseComparator icc = new IgnoreCaseComparator();
    
    java.util.Collections.sort(arrayList,icc);
    

    【讨论】:

    • 我试过这个。它可以工作,但问题是我的数组列表包含以大写字母和小写字母开头的名称。通过使用此逻辑,它首先显示以大写字母开头的名称排序列表,然后其他。我想同时对大写和小写进行排序。
    • 同时意味着,你需要忽略大小写并按大小写排序,还是按大小写排序...?
    • @Seethelakshmi:尝试使用这个Collections.sort(path, String.CASE_INSENSITIVE_ORDER);,这将忽略大小写并比较你的字符串......
    • @Seethalakshmi:我已经编辑了我的答案,看看它:)
    • @侯赛因,感谢您的回答。我已经尝试了从 A1 到 A10 的 ArrayList 解决方案,但 A10 没有正确排序。不知何故,A10 追随 A1。基本上,它排序为 A1、A10、A2、A3 等。为什么会发生这种情况以及如何正确排序列表?
    【解决方案2】:
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class ArrayListSortExample {
    public static void main(String[] args) {
    /*
    * Create a collections of colours
    */
    List colours = new ArrayList();
    colours.add("red");
    colours.add("green");
    colours.add("blue");
    colours.add("yellow");
    colours.add("cyan");
    colours.add("white");
    colours.add("black");
    
    /*
    * We can sort items of a list using the Collections.sort() method.
    * We can also reverse the order of the sorting by passing the
    * Collections.reverseOrder() comparator.
    */
    Collections.sort(colours);
    System.out.println(Arrays.toString(colours.toArray()));
    
    Collections.sort(colours, Collections.reverseOrder());
    System.out.println(Arrays.toString(colours.toArray()));
    }
    

    【讨论】:

    • ur ansr 也很有用 4 me.but d 相同的 prblm 声明 abv 出现了。如果你能帮助我
    【解决方案3】:

    嗨 seethalakshmi 用于在 Arraylist 上进行排序,您需要比较器和集合

    只要通过这个链接http://ventrix.nsdc.gr/code_folds/?p=119,你就可以轻松实现它

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 2011-07-28
      • 2014-02-09
      • 2014-12-07
      • 1970-01-01
      相关资源
      最近更新 更多