Search code examples
javajava-8java-streamdeclarative-programming

Find if a string from one Set is substring of string from another Set using declarative style?


I have two Sets of strings, I need to find if a string is substring of any string from another Set. Below is the equivalent code in imperative style.

boolean elementContains() {
    Set<String> set1 = Set.of("abc","xyz","mnop");
    Set<String> set2 = Set.of("hello.world.mnop", "hello.world", "foo.bar");

    for (String str: set1) {
        for (String str2: set2) {
            if(str2.contains(str)) { //XXX: contains not equals
                return true;
            }
        }
    }
    return false;
}

I came up with declarative code which is not very eloquent.

boolean elementContains() {
    Set<String> set1 = Set.of("abc","xyz","mnop");
    Set<String> set2 = Set.of("hello.world.mnop", "hello.world", "foo.bar");

    Optional<String> first = set1.stream()
            .filter(ele -> {
                Optional<String> first1 = set2.stream()
                        .filter(ele2 -> ele2.contains(ele))
                        .findFirst();
                return first1.isPresent();
            }).findFirst();

    return first.isPresent();
}

is there a way to write the same code fluently?


Solution

  • You can replace the findFirst + isPresent combination with something on the lines of using anyMatch and that would simplify the code significantly :

    Set<String> set1 = Set.of("abc", "xyz", "mnop");
    Set<String> set2 = Set.of("hello.world.mnop", "hello.world", "foo.bar");
    return set1.stream()
            .anyMatch(ele -> set2.stream()
                    .anyMatch(ele2 -> ele2.contains(ele)));