Search code examples
javaguava

How to check if a List<String> is sorted matching a specific pattern in Guava?


I'm trying to check if a List<String> elements are sorted by the first character of its elements to match this format (Blank, Numbers, Letters) the blank is literally an 8 spaces string " "

I tried this with no avail

Ordering.from(String.CASE_INSENSITIVE_ORDER).isOrdered(abc);

I wanna do this with Guava, I successfully did this with three for loops.


Solution

  • As you are not using a natural ordering of strings you will have to implement your own comparator. Here you have te official Comparator documentation. According to the documentation the Comparator interface is:

    A comparison function, which imposes a total ordering on some collection of objects.

    And it's comparison function will return:

    a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

    You can use the method from() of Ordered class. This method takes as a parameter a custom Comparator that will do the task of comparing strings:

    public boolean isOrdered(List<String> list) {
            return Ordering.from(getComparator()).isOrdered(list);
    }
    

    The getComparator() function will return this Comparator:

    public Comparator<String> getComparator() {
        return new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                char firstChar1 = o1.charAt(0);
                char firstChar2 = o2.charAt(0);
                if (o1.startsWith("        ")) {
                    return o2.startsWith("        ") ? 0 : -1;
                } else if (o2.startsWith("        ")) {
                    return o2.startsWith("        ") ? 0 : 1;
                } else if (firstChar1 == firstChar2) {
                    return 0;
                } else {
                    return firstChar1 - firstChar2 < 0 ? -1 : 1;
                }
            }
        };
    }
    

    I have tested above code by:

    public void myMethod() {
        List<String> ordered = Arrays.asList("        hello", "1hello", "2hello", "8hello", "hello", "zhello");
        List<String> unordered = Arrays.asList("        hello", "1hello", "8hello", "2hello", "hello", "zhello");
        System.out.println(isOrdered(ordered));
        System.out.println(isOrdered(unordered));
    }
    

    The output on the console is:

    true
    false