简体   繁体   English

如何检查一个流<String>包含另一个流<String>在 Java 8 中

[英]How to check if a Stream<String> contains another Stream<String> in Java 8

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”,那么它可以工作,但是如何检查整个流而不仅仅是字符或字符串?

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());
    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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM