public class MiniTwitter {
class Node {
public int order;
public Tweet tweet;
public Node(int o, Tweet t) {
this.order = o;
this.tweet = t;
}
}
class SortByOrder implements Comparator {
public int compare(Object obj1, Object obj2) {
Node node1 = (Node) obj1;
Node node2 = (Node) obj2;
if (node1.order < node2.order)
return 1;
else
return -1;
}
}
private Map> friends;
private Map> users_tweets;
private int order;
public List getLastTen(List tmp) {
int last = 10;
if (tmp.size() < 10)
last = tmp.size();
return tmp.subList(tmp.size() - last, tmp.size());
}
public List getFirstTen(List tmp) {
int last = 10;
if (tmp.size() < 10)
last = tmp.size();
return tmp.subList(0, last);
}
public MiniTwitter() {
this.friends = new HashMap>();
this.users_tweets = new HashMap>();
this.order = 0;
}
public Tweet postTweet(int user_id, String tweet_text) {
Tweet tweet = Tweet.create(user_id, tweet_text);
if (!users_tweets.containsKey(user_id))
users_tweets.put(user_id, new ArrayList());
order += 1;
users_tweets.get(user_id).add(new Node(order, tweet));
return tweet;
}
public List getNewsFeed(int user_id) {
List tmp = new ArrayList();
if (users_tweets.containsKey(user_id))
tmp.addAll(getLastTen(users_tweets.get(user_id)));
if (friends.containsKey(user_id)) {
for (Integer user : friends.get(user_id)) {
if (users_tweets.containsKey(user))
tmp.addAll(getLastTen(users_tweets.get(user)));
}
}
Collections.sort(tmp, new SortByOrder());
List rt = new ArrayList();
tmp = getFirstTen(tmp);
for (Node node : tmp) {
rt.add(node.tweet);
}
return rt;
}
public List getTimeline(int user_id) {
List tmp = new ArrayList();
if (users_tweets.containsKey(user_id))
tmp.addAll(getLastTen(users_tweets.get(user_id)));
Collections.sort(tmp, new SortByOrder());
List rt = new ArrayList();
tmp = getFirstTen(tmp);
for (Node node : tmp)
rt.add(node.tweet);
return rt;
}
public void follow(int from_user_id, int to_user_id) {
if (!friends.containsKey(from_user_id))
friends.put(from_user_id, new HashSet());
friends.get(from_user_id).add(to_user_id);
}
public void unfollow(int from_user_id, int to_user_id) {
if (friends.containsKey(from_user_id))
friends.get(from_user_id).remove(to_user_id);
}
}