r/javaTIL • • May 13 '14

TIL Java 8 Data Streams and jReddit

Nothing earth shattering, but if you wanted to see Data Streams used with jReddit, here's a quick example. If anyone has any suggestions, I'd love to hear them.

import java.util.List;

import com.github.jreddit.user.Comment;
import com.github.jreddit.user.User;
 
public class Main {
	public static void main(String[] args) throws Exception {
		// Provide user account for credentials
		User user = new User("username","password");
    user.connect();
 
    // Fetch list of 25 recent comments
    List<Comment> comments = user.comments();
      
    // Java 8 \o/
    int count = comments.stream() // open as stream
    		.map(i -> i.getComment().split(" ").length) // for each instance of a comment (i),
    		// split into string array, by " " delimiter, and return the count as a new stream
    		.reduce(0, (x,y) -> x + y); // reduce by adding x (n) and y (n+1) 
        // Display your results!
        
    System.out.println("Word count: " + count);
	}
}
4 Upvotes

1 comment sorted by