Hi friends,
Today we are going to find out the Top 10 Worldwide Trending Topics on Twitter with the help of twitter4j Java API.
The step by step process can be depicted in below picture. It shows the step by step algorithm which you can use in order to show top 10 Worldwide Trending Twitter Topics.

Now, what do these trending topics mean?
The simple answer is it shows what people are talking about on twitter. It kind of gives you some idea about the topics that are getting discussed over “mentioned” places. In our case, this mentioned place is the entire world i.e. we are going to retrieve the trending topics across the world.
For that we are using the following code.
package com.milind.twitter.trends; | |
import java.io.IOException; | |
import twitter4j.Trend; | |
import twitter4j.Trends; | |
import twitter4j.Twitter; | |
import twitter4j.TwitterException; | |
import twitter4j.TwitterFactory; | |
import twitter4j.conf.ConfigurationBuilder; | |
/** | |
* | |
* @author Milind | |
*/ | |
public class TwitterTrendingTopics { | |
public static void main(String[] args) throws IOException, TwitterException { | |
ConfigurationBuilder cb = new ConfigurationBuilder(); | |
cb.setDebugEnabled(true) | |
.setOAuthConsumerKey("3jmA1BqasLHfItBXj3KnAIGFB") | |
.setOAuthConsumerSecret("imyEeVTctFZuK62QHmL1I0AUAMudg5HKJDfkx0oR7oFbFinbvA") | |
.setOAuthAccessToken("265857263-pF1DRxgIcxUbxEEFtLwLODPzD3aMl6d4zOKlMnme") | |
.setOAuthAccessTokenSecret("uUFoOOGeNJfOYD3atlcmPtaxxniXxQzAU4ESJLopA1lbC"); | |
TwitterFactory tf = new TwitterFactory(cb.build()); | |
Twitter twitter = tf.getInstance(); | |
Trends trends = twitter.getPlaceTrends(1); | |
int count = 0; | |
for (Trend trend : trends.getTrends()) { | |
if (count < 10) { | |
System.out.println(trend.getName()); | |
count++; | |
} | |
} | |
} | |
} |
There are few things that we should know about the above code. Those are as follows.
- Consumer Key, Consumer Secret, Access Token and Access Token Secret are the parameters we get after creating our own twitter app at https://www.apps.twitter.com
- getPlaceTrends() method in line number 25 expects the Yahoo Place Id. In this case, we are passing it as 1 which means we want to find the trends worldwide. Similarly, you can pass any Place Id to get the trending topics for that particular place.
- The counter that we are using in line number 28 is for getting the top 10 trending topics.
Once I ran above code, I got the following output.It shows the trending topics at that particular time.

And for verification, I went to my twitter account and saw the latest trending topics on twitter.com. Following is the screenshot of the trending topics on twitter.com

As you can see from above two screenshots, both my program and twitter.com is giving the same results.
This completes our twitter4j implementation of trending topics.
Thanks for having a read.