How to sort alphabetically while ignoring case sensitive?

JavaAndroidCollections

Java Problem Overview


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

Java Solutions


Solution 1 - Java

Collections.sort(listToSort, String.CASE_INSENSITIVE_ORDER);

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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?

Solution 13 - Java

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

Solution 14 - Java

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

Solution 15 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser934357View Question on Stackoverflow
Solution 1 - JavaguyblankView Answer on Stackoverflow
Solution 2 - JavaDavid Snabel-CauntView Answer on Stackoverflow
Solution 3 - Javauser4363171View Answer on Stackoverflow
Solution 4 - JavaNickTView Answer on Stackoverflow
Solution 5 - JavaAdam GentView Answer on Stackoverflow
Solution 6 - JavaJava DevilView Answer on Stackoverflow
Solution 7 - JavaAndrejsView Answer on Stackoverflow
Solution 8 - JavaHatem BadawiView Answer on Stackoverflow
Solution 9 - JavaOusmane D.View Answer on Stackoverflow
Solution 10 - Javayome fissehaView Answer on Stackoverflow
Solution 11 - Javauser3561002View Answer on Stackoverflow
Solution 12 - JavadenolkView Answer on Stackoverflow
Solution 13 - JavaHugo SilvaView Answer on Stackoverflow
Solution 14 - JavaCarlosLeoView Answer on Stackoverflow
Solution 15 - JavaNilesh PatilView Answer on Stackoverflow