Last active
October 11, 2015 12:17
-
-
Save aruld/3857575 to your computer and use it in GitHub Desktop.
Filter tweets matching keywords using anyMatch() and reduce() operations on the Stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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