如何检查 List<String> 是否与 Guava 中的特定模式匹配?

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

我正在尝试检查 List<String> 元素是否按其元素的第一个字符排序 匹配这种格式 (空白、数字、字母) 空格实际上是一个 8 个空格的字符串 " "

我试过了没有用

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

我想用番石榴做这个,我用三个 for 循环成功地做到了。

由于您没有使用自然排序的字符串,因此您必须实现自己的比较器。这里有官方 Comparator documentation。根据文档,比较器接口是:

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

它的比较函数将return:

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

可以使用Orderedclass的方法from()。此方法将一个自定义比较器作为参数,该比较器将执行比较字符串的任务:

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

getComparator() 函数将 return 这个 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;
            }
        }
    };
}

我已经通过以下方式测试了上面的代码:

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

控制台上的输出是:

true
false