Filter tweets matching keywords using anyMatch() and reduce() operations on the Stream
List<String> google = Arrays.asList("android", "Android", "galaxy", "Galaxy", "nexus", "Nexus"); | |
List<String> apple = Arrays.asList("ios", "iOS", "iphone", "iPhone", "ipad", "iPad"); | |
List<Tweet> tweets = TweetReader.fromTweetSet(TweetReader.allTweets); | |
// Using anyMatch and method reference | |
List<Tweet> googleTweets = tweets.stream().filter(t -> (google.stream().anyMatch(t.text::contains))).collect(toList()); | |
List<Tweet> appleTweets = tweets.stream().filter(t -> (apple.stream().anyMatch(t.text::contains))).collect(toList()); | |
// Using reduce | |
List<Tweet> googleTweets2 = tweets.stream().filter(t -> google.stream().reduce(false, (Boolean b, String keyword) -> b || t.text.contains(keyword), (l, r) -> l | r)).collect(toList()); | |
List<Tweet> appleTweets2 = tweets.stream().filter(t -> apple.stream().reduce(false, (Boolean b, String keyword) -> b || t.text.contains(keyword), (l, r) -> l | r)).collect(toList()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment