0

There are some products on a Product Listing page. I'm automating a A-Z sorting functionality. To cross verify whether website sorting option working fine, I'm adding all available product in a list and using Collection.sort() method as its not working as expected.

This is my piece of code looks like :

  public static void main(String[] args) {
        List<String> x = new ArrayList<>();
        x.add("Liquid Egg Whites");
        x.add("LiquiFlav™");
        Collections.sort(x);
        System.out.println(x);
    }

Output:

[LiquiFlav™, Liquid Egg Whites]

While expected should be:

[Liquid Egg Whites, LiquiFlav™]

As per alphabetical order Liquid Egg Whites should come first.

Can anyone please explain why this happening ? and other method to get the expected result.

Michael
  • 41,989
  • 11
  • 82
  • 128
NarendraR
  • 7,577
  • 10
  • 44
  • 82
  • It's comparing using the character encoding, and the character `F`, which is uppercase, comes before the character `d`, which is lowercase – user May 04 '20 at 15:21
  • 5
    `Collections.sort(x, String.CASE_INSENSITIVE_ORDER);` – Holger May 04 '20 at 15:24
  • 3
    Or even better, `Collections.sort(x, Collator.getInstance());`, which is designed for sorting human-readable text. – VGR May 04 '20 at 15:44

1 Answers1

4

According to string comparison rules, upper case characters have greater precedence over lower case characters Eg : "abcdefG" > "abcdefaa", "xyzA" > "xyza"

Similarly, "LiquiFlav" > "Liquid Egg Whites"

So, the response you got is correct.

Edit : You can make use of Collections.sort(x,String.CASE_INSENSITIVE_ORDER) to get the output as you desired.