开发者

How to sort alphabetically while ignoring case sensitive?

开发者 https://www.devze.com 2023-04-06 00:42 出处:网络
I have this code, but works only for lower case letters.I want this to sort the list while ignoring the upper case letters..

I have this code, but works only for lower case letters. I want this to sort the list while ignoring the upper case letters..

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

    }
    }
}


Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);


It is very unclear what you are trying to do, but you can sort a list like this:

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


Collections.sort() lets you pass a custom comparator for ordering. For case insensitive ordering String class provides a static final comparator called CASE_INSENSITIVE_ORDER.

So in your case all that's needed is:

Collections.sort(caps, String.CASE_INSENSITIVE_ORDER);


Here's a plain java example of the best way to do it:

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


I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.

You should almost always use a Collator for dictionary based sorting.

For case insensitive collator searching for the English language you do the following:

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


Since Java 8 you can sort using the Streams API:

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

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

The difference with Collections.sort is that this will return a new list and will not modify the existing one.


I like the comparator class SortIgnoreCase, but would have used this

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


Array Sorting in Java 8 Way-> Easy peasy lemon squeezy

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

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

I used method Reference String::compareToIgnoreCase


Pass java.text.Collator.getInstance() to Collections.sort method ; it will sort Alphabetically while ignoring case sensitive.

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


You can directly call the default sort method on the list like this:

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

or:

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


In your comparator factory class, do something like this:

 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;

This uses the compare to method which is case insensitive (why write your own). This way you can use Collections sort like this:

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


did you tried converting the first char of the string to lowercase on if(fruits[i].charAt(0) == currChar) and char currChar = fruits[0].charAt(0) statements?


Example using Collections and ArrayList:

Develop an intern static class like the example "CompareStrings".

Call the intern static class in the main method.

Easy to understand and works fine!

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


In your case you have a List of Strings and most of the already proposed solutions (I specially like @guyblank answer) are just fine but!!!, if you have a List of beans, which is my case, you can use Comparable interface in your bean like this:

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

}

Then you only need to create your ArrayList<UserBean> userBeanArray = new ArrayList<UserBean>();, fill it and sort it: Collections.sort(userBeanArray);

And you have it done!

Hope to help to community ;-)


We can pass both the field and the caseInsensitivitive in Comparator

Collections.sort(list, Comparator.comparing(Ticket::getName, String.CASE_INSENSITIVE_ORDER));


Here is an example to sort an array : Case-insensitive

import java.text.Collator;
import java.util.Arrays;

public class Main {
  public static void main(String args[]) {

    String[] myArray = new String[] { "A", "B", "b" };
    Arrays.sort(myArray, Collator.getInstance());

  System.out.println(Arrays.toString(myArray));

 }

}

/* Output:[A, b, B] */

0

精彩评论

暂无评论...
验证码 换一张
取 消