我使用Collection.disjoint查找两个字符串集合的不相交集c1, c2.,但它不忽略大小写,例如-stringstrStr不同。

return Collections.disjoint(c1, c2);

如果不使用for循环,是否可以找到忽略其案例的两个集合的不相交?

最佳答案

如果您绝对坚持不使用for循环,则始终可以找到小写Collections的两个Strings之间的不相交。使用Google Guava时,应该类似于:

package ru.zombator.stackoverflow;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;

public final class DisjointIgnoreCase {
    public static void main(String[] args) {
        Collection<String> coll1 = Arrays.asList("donald", "Duck");
        Collection<String> coll2 = Arrays.asList("DONALd", "Donut");
        Collection<String> coll3 = Arrays.asList("Homer", "DONUT");
        Collection<String> coll4 = Arrays.asList("DONALD", "duck");

        // will all print false
        System.out.println(disjointIgnoreCase(coll1, coll2));
        System.out.println(disjointIgnoreCase(coll2, coll3));
        System.out.println(disjointIgnoreCase(coll1, coll4));

        // will print true (no common elements)
        System.out.println(disjointIgnoreCase(coll1, coll3));
    }

    private static boolean disjointIgnoreCase(Collection<String> coll1, Collection<String> coll2) {
        return Collections.disjoint(lowercased(coll1), lowercased(coll2));
    }

    private static Collection<String> lowercased(Collection<String> coll) {
        return Collections2.transform(coll, new Function<String, String>() {
            @Override
            public String apply(String input) {
                return input.toLowerCase(Locale.US);
            }
        });
    }
}

10-07 15:25