Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 507
jimakos17 Avatar asked Oct 20 '25 02:10

jimakos17


1 Answers

You need to collect the second stream and store all its values in some adapted data strucutre.

For example using a Set:

Set<String> secondSet = second.collect(Collectors.toSet());
List<String> f = first.filter(s -> secondSet.contains(s))
                      .collect(Collectors.toList());
like image 189
Jean Logeart Avatar answered Oct 22 '25 16:10

Jean Logeart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!