1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Twitter { private Map<Integer, User> users;
public Twitter() { this.users = new HashMap<>(); }
public void postTweet(int userId, int tweetId) { Tweet tweet = new Tweet(tweetId, System.nanoTime()); User user = this.users.getOrDefault(userId, createUser(userId)); user.getTweets().addFirst(tweet); if (user.getTweets().size() > 10) { user.getTweets().subList(0, 10); } this.users.put(userId, user); }
public List<Integer> getNewsFeed(int userId) { if (this.users.containsKey(userId)) { List<Tweet> tweets = new LinkedList<>(); tweets.addAll(this.users.get(userId).getTweets()); this.users.get(userId).getFollowerIds().stream().map(this.users::get).map(User::getTweets).forEach(list -> tweets.addAll(list)); List<Integer> result = tweets.stream().sorted(Comparator.reverseOrder()).distinct().map(Tweet::getTweetId).collect(Collectors.toList()); return result.size() > 10 ? result.subList(0, 10) : result; } return new ArrayList<>(); }
public void follow(int followerId, int followeeId) { User follower = this.users.getOrDefault(followerId, createUser(followerId)); follower.getFollowerIds().add(followeeId); this.users.put(followerId, follower); User followee = this.users.getOrDefault(followeeId, createUser(followeeId)); followee.getFolloweeIds().add(followerId); this.users.put(followeeId, followee); }
public void unfollow(int followerId, int followeeId) { this.users.get(followerId).getFollowerIds().remove((Object) followeeId); this.users.get(followeeId).getFolloweeIds().remove((Object) followerId); }
private User createUser(Integer userId) { return new User(userId, new ArrayList<>(), new ArrayList<>(), new LinkedList<>()); } }
|