it-swarm.cn

如何在不区分大小写的情况下按字母顺序排序?

我有此代码,但仅适用于小写字母。我希望它在不考虑大写字母的情况下对列表进行排序。

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);

    }
    }
}
44
user934357

这是一个简单的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());
        }
    }
}
30
NickT
Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);
140
guyblank

非常不清楚您要做什么,但是您可以对列表进行如下排序:

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);
39
David Snabel-Caunt

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

因此,您需要做的是:

Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);
30
user4363171

我不敢相信没有人提到 Collat​​or 。几乎所有这些答案仅适用于英语。

您几乎应该始终使用 用于基于字典的排序的整理程序

对于不区分大小写的整理器,如果要搜索英语,请执行以下操作:

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

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

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

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());
3
Hatem Badawi

由于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的区别在于,这将返回一个新列表,并且不会修改现有列表。

2
Andrejs

您可以像这样直接在列表上调用默认的 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
1
Aomine

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

 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());
1
user3561002

在您的情况下,您有List个字符串,并且大多数已经提出的解决方案(我特别喜欢@guyblank答案)都可以,但是!!!!如果您有List个bean,在我的情况下,您可以在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);

事情就完成了!

希望对社区有帮助;-)

0
CarlosLeo

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

0
denolk

使用Collections和ArrayList的示例:

开发一个内部静态类,例如“ CompareStrings”示例。

在main方法中调用intern静态类。

易于理解,工作正常!

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);
        }
    }
}
0
Hugo Silva