'Find disjoint set irrespective of case of the strings
I am using Collection.disjoint to find the disjoint set of two string collections c1, c2. But it does not ignore cases, for example - string str is different than Str.
return Collections.disjoint(c1, c2);
Can I find the disjoint of both collections ignoring their cases without using a for loop?
Solution 1:[1]
If you absolutely insist that no for loop is used, you can always find the disjoint between two Collections of lowercased Strings. Using Google Guava, it should be something like:
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);
}
});
}
}
Solution 2:[2]
An easier way is to convert the values of both lists to lowercase. Creating new lists is not needed as the function is applied to the values the value references are the same - inplace change.
c1.stream().map(s -> s.toLowerCase()).collect(Collectors.toList());
c2.stream().map(s -> s.toLowerCase()).collect(Collectors.toList());
Collections.disjoint(c1, c2);
One cannot put directly the mapping in the disjoint because multiple levels of processing is not allowed here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nvamelichev |
| Solution 2 | Petronella |
