Search code examples
javatwittertwitter4j

Twitter4j get followers who have most follower count


Im using twitter 4j for an small twitter application and im currently using the following code to get the followers ids, what i need is for an user(let says ME) i like to have top 10 user who have most followers count( the following code gets profileIDs of an user). in my twitter profile i got 80 followers and i like to fetch followers who have more followers(first 10)

Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
String accessToken = getSavedAccessToken();
String accessTokenSecret = getSavedAccessTokenSecret();
AccessToken oathAccessToken = new AccessToken(accessToken, accessTokenSecret);

twitter.setOAuthAccessToken(oathAccessToken);
User user = null;
try {
    user = twitter.showUser(username);// id = user.getId();
} catch (TwitterException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Solution

  • To retrieve followers of a given user using their screen name, see Twitter#getFollowersList(), for example:

    long cursor = -1;
    PagableResponseList<User> followers;
    do {
         followers = twitter.getFollowersList("screenName", cursor);
        for (User follower : followers) {
            // TODO: Collect top 10 followers here
            System.out.println(follower.getName() + " has " + follower.getFollowersCount() + " follower(s)");
        }
    } while ((cursor = followers.getNextCursor()) != 0);
    

    I've used a cursor to retrieve all the followers, by default the api call only returns twenty - see Twitter's guide on Using cursors to navigate for more information.

    Within the for-loop you can collect your 'top 10' followers by inspecting the followers count.