找到不相交的集合,不管字符串的大小写

时间:2014-03-19 22:01:53

标签: java collections set

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

return Collections.disjoint(c1, c2);

我可以在不使用for循环的情况下找到两个集合的不相交而忽略它们的情况吗?

1 个答案:

答案 0 :(得分:1)

如果您绝对坚持不使用for循环,则始终可以找到两个Collection小写String之间的不相交。使用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);
            }
        });
    }
}