Get recent twitter followers using Twitter4j

25 / Sep / 2012 by Vishal Sahu 2 comments


In the previous blog we saw how to fetch twitter users based on some search criteria using the Twitter4j library, a java wrapper available for Twitter API calls.

In the same grails project, i had the requirement to display the recent twitter followers of authenticated twitter accounts. Twitter4j library provides a way to get the IDs of twitter followers in the ordered way, which can further be used to get the information of the latest followers. It helped me a lot to make quick list of user’s recent followers on twitter.

Twitter API needs to have twitter account access_token and access_secret, which we obtains after authorizing/connecting twitter account with the application as mentioned in this blog.

Code to fetch recent twitter followers:-


TwitterFactory factory = new TwitterFactory()
Twitter twitter = factory.getInstance()
twitter.setOAuthConsumer(consumerKey, consumerSecret)
AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
String twitterScreenName = twitter.getScreenName()
IDs followerIDs = twitter.getFollowersIDs(twitterScreenName, -1)
List<Integer> followerIdList = followerIDs.IDs
if (followerIdList?.size() > 0) {
int numberOfFollowers = Math.min(followerIdList.size(), 20)
followerIdList = followerIdList.subList(0, numberOfFollowers)
followerIdList.each {
twitter4j.User user = twitter.showUser(it)
println("Name: ${user.screenName}")
println("Location: ${user.location}")


This code will fetch the recent 20 followers from the user’s twitter account.

Hope this helps.


comments (2)

  1. akhilesh

    List followerIdList = followerIDs.IDs- here i got an error that “IDs cannot be resolved or is not a field”
    twitter4j.User user = twitter.showUser(it) here also i got an error that “it cannot be resolved to a variable”
    sorry i am beginner .. pls help me thanks in advance


Leave a Reply

Your email address will not be published. Required fields are marked *