import com.twingly.search.Query;
import com.twingly.search.QueryBuilder;
import com.twingly.search.client.Client;
import com.twingly.search.client.UrlConnectionClient;
import com.twingly.search.domain.Post;
import com.twingly.search.domain.Result;

import java.util.Date;

public class SearchPostsStream {
    private static final String USER_AGENT = "MyCompany/1.0";
    private Query q;
    private Client client;
    private int counter;

    public SearchPostsStream(String keyword) {
        q = QueryBuilder.create(String.format("sort-order:asc sort:published %s", keyword)).build();
        client = new UrlConnectionClient();
        client.setUserAgent(USER_AGENT);
    }

    public static void main(String[] args) {
        // set java system property TWINGLY_SEARCH_KEY
        SearchPostsStream searchPostsStream = new SearchPostsStream("(github) AND (hipchat OR slack)");
        searchPostsStream.each();
        System.out.println("Iterated through " + searchPostsStream.getCount() + " results");
    }

    public void each() {
        Result result = client.makeRequest(q);
        iterateAllPosts(result);
    }

    public int getCount() {
        return counter;
    }

    private void iterateAllPosts(Result result) {
        for (Post post : result.getPosts()) {
            System.out.println(post.getUrl());
            counter++;
        }
        if (result.areAllResultsReturned()) {
            return;
        }
        Post lastPost = result.getPosts().get(result.getPosts().size() - 1);
        Date lastPublishedAt = lastPost.getPublishedAt();
        q = q.toBuilder().startTime(lastPublishedAt).build();
        Result newResult = client.makeRequest(q);
        iterateAllPosts(newResult);
    }
}

@@ -1,37 +1,4 @@
-import com.twingly.search.Query;%0A
 impo
@@ -33,16 +33,16 @@
 uilder;%0A
+
 import c
@@ -345,18 +345,36 @@
 te Query
- q
+Builder queryBuilder
 ;%0A    pr
@@ -476,16 +476,27 @@
        q
+ueryBuilder
  = Query
@@ -569,24 +569,16 @@
 eyword))
-.build()
 ;%0A      
@@ -1062,32 +1062,51 @@
 nt.makeRequest(q
+ueryBuilder.build()
 );%0A        itera
@@ -1591,24 +1591,34 @@
    q
- = q.to
+ueryBuilder = query
 Builder
-()
 .sta
@@ -1640,24 +1640,16 @@
 ishedAt)
-.build()
 ;%0A      
@@ -1689,16 +1689,35 @@
 equest(q
+ueryBuilder.build()
 );%0A     

Use QueryBuilder inside SearchPostsStream instead of Query