How to Sort Alphabetically While Ignoring Case Sensitive

How to sort alphabetically while ignoring case sensitive?

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

Java: How to sort an ArrayList alphabetically with case insensitive and with any number Strings at the end

Composition

Create your own Comparator<String>. Test for digits first, then and use String.CASE_INSENSITIVE_ORDER.

public class MyStringComparator implements Comparator<String> {
public int compareTo(String a, String b) {
//if both a and b are digits, maybe use String.CASE_INSENSITIVE_ORDER?
//if a is all digits return -1
//if b is all digits return 1
return String.CASE_INSENSTIVE_ORDER(a,b);
}
}

case-insensitive list sorting, without lowercasing the result?

In Python 3.3+ there is the str.casefold method that's specifically designed for caseless matching:

sorted_list = sorted(unsorted_list, key=str.casefold)

In Python 2 use lower():

sorted_list = sorted(unsorted_list, key=lambda s: s.lower())

It works for both normal and unicode strings, since they both have a lower method.

In Python 2 it works for a mix of normal and unicode strings, since values of the two types can be compared with each other. Python 3 doesn't work like that, though: you can't compare a byte string and a unicode string, so in Python 3 you should do the sane thing and only sort lists of one type of string.

>>> lst = ['Aden', u'abe1']
>>> sorted(lst)
['Aden', u'abe1']
>>> sorted(lst, key=lambda s: s.lower())
[u'abe1', 'Aden']

How to perform case-insensitive sorting array of string in JavaScript?

In (almost :) a one-liner

["Foo", "bar"].sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});

Which results in

[ 'bar', 'Foo' ]

While

["Foo", "bar"].sort();

results in

[ 'Foo', 'bar' ]

Sorting string value in a case-insensitive manner in Java 8

Try this

Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)

Simple way to sort strings in the (case sensitive) alphabetical order

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
public int compare(String str1, String str2) {
int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
if (res == 0) {
res = str1.compareTo(str2);
}
return res;
}
};

Collections.sort(list, ALPHABETICAL_ORDER);

And I think it is just as easy to understand and code ...

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);

Sorting a String array and ignoring case

You can use String method localizedCompare()

update: Xcode 11.5 • Swift 5.2

let array = ["def","Ghi","Abc" ]

let sorted1 = array.sorted{$0.compare($1) == .orderedAscending}
print(sorted1) // ["Abc", "Ghi", "def"] this is case SENSITIVE!

let sorted2 = array.sorted{$0.localizedCompare($1) == .orderedAscending}
print(sorted2) // ["Abc", "def", "Ghi"]

// you can also use the String compare options parameter to give you more control when comparing your strings
let sorted3 = array.sorted{$0.compare($1, options: .caseInsensitive) == .orderedAscending }
print(sorted3) // ["Abc", "def", "Ghi"]\n"

// which can be simplifyed using the string method caseInsensitiveCompare
let sorted4 = array.sorted{$0.caseInsensitiveCompare($1) == .orderedAscending}
print(sorted4) // ["Abc", "def", "Ghi"]\n"

// or localizedStandardCompare (case and diacritic insensitive)
// This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact sorting behavior of this method is different under different locales and may be changed in future releases. This method uses the current locale.
let array5 = ["Cafe B","Café C","Café A"]
let sorted5 = array5.sorted { $0.localizedStandardCompare($1) == .orderedAscending }
print(sorted5) // "["Café A", "Cafe B", "Café C"]\n"

You can also implement your own custom sort/sorted methods:

extension Collection where Element: StringProtocol {
public func localizedSorted(_ result: ComparisonResult) -> [Element] {
sorted { $0.localizedCompare($1) == result }
}
public func caseInsensitiveSorted(_ result: ComparisonResult) -> [Element] {
sorted { $0.caseInsensitiveCompare($1) == result }
}
public func localizedCaseInsensitiveSorted(_ result: ComparisonResult) -> [Element] {
sorted { $0.localizedCaseInsensitiveCompare($1) == result }
}
/// This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact sorting behavior of this method is different under different locales and may be changed in future releases. This method uses the current locale.
public func localizedStandardSorted(_ result: ComparisonResult) -> [Element] {
sorted { $0.localizedStandardCompare($1) == result }
}
}


extension MutableCollection where Element: StringProtocol, Self: RandomAccessCollection {
public mutating func localizedSort(_ result: ComparisonResult) {
sort { $0.localizedCompare($1) == result }
}
public mutating func caseInsensitiveSort(_ result: ComparisonResult) {
sort { $0.caseInsensitiveCompare($1) == result }
}
public mutating func localizedCaseInsensitiveSort(_ result: ComparisonResult) {
sort { $0.localizedCaseInsensitiveCompare($1) == result }
}
/// This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact sorting behavior of this method is different under different locales and may be changed in future releases. This method uses the current locale.
public mutating func localizedStandardSort(_ result: ComparisonResult) {
sort { $0.localizedStandardCompare($1) == result }
}
}

Usage:

var array = ["def","Ghi","Abc" ]
array.caseInsensitiveSort(.orderedAscending)
array // ["Abc", "def", "Ghi"]



To sort a custom object by a string property we can pass a predicate to get the string from the element and use a keypath when calling this method:

extension Collection {
/// This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact sorting behavior of this method is different under different locales and may be changed in future releases. This method uses the current locale.
public func localizedStandardSorted<T: StringProtocol>(by predicate: (Element) -> T, ascending: Bool = true) -> [Element] {
sorted { predicate($0).localizedStandardCompare(predicate($1)) == (ascending ? .orderedAscending : .orderedDescending) }
}
}


extension MutableCollection where Self: RandomAccessCollection {
/// This method should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact sorting behavior of this method is different under different locales and may be changed in future releases. This method uses the current locale.
public mutating func localizedStandardSort<T: StringProtocol>(by predicate: (Element) -> T, ascending: Bool = true) {
sort { predicate($0).localizedStandardCompare(predicate($1)) == (ascending ? .orderedAscending : .orderedDescending) }
}
}

Usage:

struct File {
let id: Int
let fileName: String
}


var files: [File] = [.init(id: 2, fileName: "Steve"),
.init(id: 5, fileName: "Bruce"),
.init(id: 3, fileName: "alan")]

let sorted = files.localizedStandardSorted(by: \.fileName)
print(sorted) // [File(id: 3, fileName: "alan"), File(id: 5, fileName: "Bruce"), File(id: 2, fileName: "Steve")]

files.localizedStandardSort(by: \.fileName)
print(files) // [File(id: 3, fileName: "alan"), File(id: 5, fileName: "Bruce"), File(id: 2, fileName: "Steve")]

edit/update:

iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0 or later

You can use the new generic structure KeypathComparator

let sorted = files.sorted(using: KeyPathComparator(\.fileName, comparator: .localizedStandard))
print(sorted) // [File(id: 3, fileName: "alan"), File(id: 5, fileName: "Bruce"), File(id: 2, fileName: "Steve")]
let reversed = files.sorted(using: KeyPathComparator(\.fileName, comparator: .localizedStandard, order: .reverse))
print(reversed) // [File(id: 2, fileName: "Steve"), File(id: 5, fileName: "Bruce"), File(id: 3, fileName: "alan")]

files.sort(using: KeyPathComparator(\.fileName, comparator: .localizedStandard))
print(files) // [File(id: 3, fileName: "alan"), File(id: 5, fileName: "Bruce"), File(id: 2, fileName: "Steve")]

For simple types you need to use self as the KeyPath

var array = ["def","Ghi","Abc"]
let sorted = array.sorted(using: KeyPathComparator(\.self, comparator: .localizedStandard))

Or mutating the original

array.sort(using: KeyPathComparator(\.self, comparator: .localizedStandard))


Related Topics



Leave a reply



Submit