如何在 Java 8 中检查 Stream<String> 是否包含另一个 Stream<String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27933642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a Stream<String> contains another Stream<String> in Java 8
提问by jimakos17
I created two Stream
我创建了两个流
Stream<String> first= ...
Stream<String> second= ...
Both of them have numbers. Let's say the first file has 1 to 1000 and the second one has 25 to 35. I'd like to check if the first one contains the numbers of the seconds one.
他们俩都有号码。假设第一个文件有 1 到 1000,第二个文件有 25 到 35。我想检查第一个文件是否包含秒数。
first.filter(s-> !s.contains(second.toString())
.collect(Collectors.toList());
If I replace second.toString()
with "10" then it works but how can I check the whole stream and not only a char or a string?
如果我替换second.toString()
为“10”,那么它可以工作,但是我如何检查整个流而不仅仅是一个字符或字符串?
回答by Jean Logeart
You need to collect the second
stream and store all its values in some adapted data strucutre.
您需要收集second
流并将其所有值存储在一些适应的数据结构中。
For example using a Set
:
例如使用一个Set
:
Set<String> secondSet = second.collect(Collectors.toSet());
List<String> f = first.filter(s -> secondSet.contains(s))
.collect(Collectors.toList());
回答by ceyun
List<String> first = new ArrayList<String>();
List<String> second = new ArrayList<String>();
for (Integer i = 0; i < 100; i++) {
first.add(i.toString());
}
for (Integer i = 25; i < 36; i++) {
second.add(i.toString());
}
boolean result = second.stream().allMatch(
value -> first.stream().collect(Collectors.toList()).contains(value));