如何按字母顺序排序而忽略区分大小写?

时间:2011-09-19 10:41:22

标签: java android collections

我有这段代码,但仅适用于小写字母。我希望这可以对列表进行排序,同时忽略大写字母..

package sortarray.com;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class SortArray extends Activity {
    ArrayList<String[]> matchedFruits = new ArrayList<String[]>();
    TextView selection;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String fruits[] = new String[7];// Sorted array
        fruits[0] = "apple";
        fruits[1] = "apricot";
        fruits[2] = "banana";
        fruits[3] = "mango";
        fruits[4] = "melon";
        fruits[5] = "pineapple";
        fruits[6] = "peach";
        char currChar = fruits[0].charAt(0);// Get first char of first element

        boolean match = false;
        int len = fruits.length;
        List<String> tmp = new ArrayList<String>();

        for (int i = 1; i < len; i++) {
            Log.d("Comparing ", fruits[i].charAt(0) + "," + currChar);
            if (fruits[i].charAt(0) == currChar) {
                if (match == false)// new match?
                {
                    match = true;// Reset search
                    tmp.clear();// clear existing items
                    tmp.add(fruits[i - 1]);
                    Log.d("Started new list ", fruits[i - 1]);
                } else {
                    tmp.add(fruits[i - 1]);
                    Log.d("Added to list ", fruits[i - 1]);
                }
            } else {
                match = false;
                tmp.add(fruits[i - 1]);
                matchedFruits.add(tmp.toArray(new String[tmp.size()]));// add to
                                                                        // final
                                                                        // list
                Log.d("Finished a list ", fruits[i - 1]);
                tmp.clear();// clear existing items

            }
            currChar = fruits[i].charAt(0);

        }
        tmp.add(fruits[len - 1]);
        matchedFruits.add(tmp.toArray(new String[tmp.size()]));// add left over
                                                                // items
        printList();
    }

    void printList()
    {
    //Print the list 
        TextView selection = (TextView) findViewById(R.id.tv);
        String mssg="";
    for(int i=0;i<matchedFruits.size();i++)
    {
            String tmp2[]= matchedFruits.get(i);

            for (int j = 0; j < tmp2.length; j++) {
                //Log.d("Final list", "Array #" + i + "[" + j + "]," + tmp2[j]);
                mssg += tmp2[j].toString();

            }
            //selection.setText("\n");
            selection.setText(mssg);

    }
    }
}

15 个答案:

答案 0 :(得分:136)

Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);

答案 1 :(得分:38)

非常不清楚您要执行的操作,但您可以对此列表进行排序:

List<String> fruits = new ArrayList<String>(7);

fruits.add("Pineapple");
fruits.add("apple");
fruits.add("apricot");
fruits.add("Banana");
fruits.add("mango");
fruits.add("melon");        
fruits.add("peach");

System.out.println("Unsorted: " + fruits);

Collections.sort(fruits, new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {              
        return o1.compareToIgnoreCase(o2);
    }
});

System.out.println("Sorted: " + fruits);

答案 2 :(得分:30)

这是一个简单的Java示例,说明了最好的方法:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Sorter {
    String fruits[] = new String[7];
    List<String> lst;

    Sorter() {
        lst = new ArrayList<String>();
        // initialise UNSORTED array
        fruits[0] = "Melon"; fruits[1] = "apricot"; fruits[2] = "peach";
        fruits[3] = "mango"; fruits[4] = "Apple";   fruits[5] = "pineapple";
        fruits[6] = "banana";
    }

    public static void main(String[] args) {
        Sorter srt = new Sorter();
        srt.anyOldUnstaticMethod();

    }
    public void anyOldUnstaticMethod() {
        Collections.addAll(lst, fruits);
        System.out.println("Initial List");
        for (String s : lst)
            System.out.println(s);
        Collections.sort(lst);
        System.out.println("\nSorted List");
        for (String s : lst)
            System.out.println(s);
        Collections.sort(lst, new SortIgnoreCase());
        System.out.println("\nSorted Ignoring Case List");
        for (String s : lst)
            System.out.println(s);
    }

    public class SortIgnoreCase implements Comparator<Object> {
        public int compare(Object o1, Object o2) {
            String s1 = (String) o1;
            String s2 = (String) o2;
            return s1.toLowerCase().compareTo(s2.toLowerCase());
        }
    }
}

答案 3 :(得分:29)

Collections.sort()允许您传递自定义比较器以进行排序。对于不区分大小写的排序String类,提供了一个名为CASE_INSENSITIVE_ORDER的静态最终比较器。

因此,在您的情况下,所需要的只是:

Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);

答案 4 :(得分:12)

我无法相信没有人提到Collator。几乎所有这些答案都只适用于英语。

您几乎应该始终使用Collator for dictionary based sorting

对于不区分大小写的搜索英语的搜索,您可以执行以下操作:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);

答案 5 :(得分:4)

我喜欢比较器类SortIgnoreCase,但是会使用这个

public class SortIgnoreCase implements Comparator<String> {
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);    // Cleaner :)
    }
}

答案 6 :(得分:3)

java.text.Collator.getInstance()传递给Collections.sort方法;它将按字母顺序排序,而忽略区分大小写。

        ArrayList<String> myArray = new ArrayList<String>();
        myArray.add("zzz");
        myArray.add("xxx");
        myArray.add("Aaa");
        myArray.add("bb");
        myArray.add("BB");
        Collections.sort(myArray,Collator.getInstance());

答案 7 :(得分:1)

在比较器工厂类中,执行以下操作:

 private static final Comparator<String> MYSTRING_COMPARATOR = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
      return s1.compareToIgnoreCase(s2);
    }
  };

  public static Comparator<String> getMyStringComparator() {
    return MYSTRING_COMPARATOR;

这使用了不区分大小写的compare to方法(为什么要编写自己的方法)。这样您可以使用这样的集合排序:

List<String> myArray = new ArrayList<String>();
//fill your array here    
Collections.sort(MyArray, MyComparators. getMyStringComparator());

答案 8 :(得分:1)

从Java 8开始,您可以使用Streams API进行排序:

List<String> fruits = Arrays.asList("apple", "Apricot", "banana");

List<String> sortedFruit = fruits.stream()
      .sorted(String.CASE_INSENSITIVE_ORDER)
      .collect(Collectors.toList())

Collections.sort的区别在于,这将返回一个新列表,不会修改现有列表。

答案 9 :(得分:0)

您是否尝试在if(fruits[i].charAt(0) == currChar)char currChar = fruits[0].charAt(0)语句中将字符串的第一个字符转换为小写?

答案 10 :(得分:0)

使用Collections和ArrayList的示例:

开发一个实习生静态类,例如“CompareStrings”。

在main方法中调用实习生静态类。

易于理解且工作正常!

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class MainClass {
    public static void main(String[] args) {
        ArrayList<String> myArray = new ArrayList<String>();
        myArray.add("zzz");
        myArray.add("xxx");
        myArray.add("Aaa");
        myArray.add("bb");
        myArray.add("BB");
        Collections.sort(myArray, new MainClass.CompareStrings());
        for(String s : myArray) {
            System.out.println(s);
        }
    }

    public static class CompareStrings implements Comparator<String> {
        @Override
        public int compare(String s1, String s2) {
           return s1.compareToIgnoreCase(s2);
        }
    }
}

答案 11 :(得分:0)

在你的情况下你有一个List的字符串和大多数已经提出的解决方案(我特别喜欢@guyblank的答案)都很好但是!!!,如果你有一个List豆子,在我的情况下,您可以在bean中使用Comparable接口,如下所示:

public class UserBean implements Comparable<UserBean> {

   private String name;
   private String surname;        
   private Integer phone;

   // GETTERS AND SETTERS

   public int compareTo(UserBean bean) {
       return name.compareToIgnoreCase(bean.name);
   }

}

然后,您只需创建ArrayList<UserBean> userBeanArray = new ArrayList<UserBean>();,填写并排序:Collections.sort(userBeanArray);

你完成了它!

希望对社区有所帮助; - )

答案 12 :(得分:0)

您可以直接在列表中调用默认的sort方法,如下所示:

myList.sort(String.CASE_INSENSITIVE_ORDER); // reads as the problem statement and cleaner

或:

myList.sort(String::compareToIgnoreCase);  // reads as the problem statement and cleaner

答案 13 :(得分:0)

Java 8方式中的数组排序->轻松榨柠檬

String[] names = {"Alexis", "Tim", "Kyleen", "KRISTY"};

  Arrays.sort(names, String::compareToIgnoreCase);

我使用了方法参考String::compareToIgnoreCase

答案 14 :(得分:-1)

以下是对数组进行排序的示例:不区分大小写

{{1}}

/ *输出:[A,b,B] * /