[英]Find if a string from one Set is substring of string from another Set using declarative style?
我有兩個Sets
的字符串,我需要找到一個字符串的子串,從另一組的任何字符串。 下面是命令式風格的等效代碼。
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;
}
我想出了不是很雄辯的聲明性代碼。
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();
}
有沒有辦法流暢地編寫相同的代碼?
您可以將findFirst
+ isPresent
組合替換為使用anyMatch
,這將顯着簡化代碼:
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)));
這與您要求的有點不同。 但是,它會告訴您是否存在任何字符串匹配。 除非必須在您的問題中使用流,否則我更願意使用您已有的簡單 for 循環。 如果您讓我知道它對您沒有幫助,我會將其刪除。
該代碼獲取 set2 的每個元素並檢查在流式 set1 中是否有任何匹配項。
import java.util.Set;
import java.util.stream.Collectors;
public class Temp {
public static void main(String [] args){
Set<String> set1 = Set.of("abc","xyz","mnop");
Set<String> set2 = Set.of("hello.world.mnop", "hello.world", "foo.bar");
Set<String> filtered = setContains(set1, set2);
filtered.forEach(System.out::println);
}
//Gives a set of elements of set2 which contain one or more elements of set1.
public static Set<String> setContains(Set<String> set1, Set<String> set2){
Set<String> result = set2
.stream()
.filter(
//Filter an s2 if it contains at any s1.
s2 -> set1
.stream()
.filter( s1 -> s2.contains(s1) )
//Make a set of s1's which are present in a given s2.
.collect( Collectors.toSet() )
//If the set has some values for a given s2, then we can accept that s2.
.size() > 0
)
.collect(Collectors.toSet());
return result;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.