Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@aruld
Last active October 11, 2015 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruld/3857575 to your computer and use it in GitHub Desktop.
Save aruld/3857575 to your computer and use it in GitHub Desktop.
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