[java] How to sort alphabetically while ignoring case sensitive?

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

    }
    }
}

This question is related to java android collections

The answer is


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

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


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

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

Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);

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?


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

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

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

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.


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] */


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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?