Java OO design with a stack and a map


  • 0
    I

    If we can use a database, we can have a better and more OO design. In here we have in-memory data structure that stores the posts and follower map. The code can be cleaner. The getNewsFeed is not optimal but it's an easy way to implement.

    public class Twitter {
    
        public Stack<Post> posts;
        public Map<Integer, Set<Integer>> followMap;
    
        public class Post {
            public int userId;
            public int tweetId;
            
            public Post(int userId, int tweetId) {
                this.userId = userId;
                this.tweetId = tweetId;
            }
        }
        
        public Twitter() {
            this.followMap = new HashMap<>();
            this.posts = new Stack<>();
        }
        
        public void postTweet(int userId, int tweetId) {
            Post post = new Post(userId, tweetId);
            posts.push(post);
        }
        
        public List<Integer> getNewsFeed(int userId) {
            List<Integer> feeds = new ArrayList<>();
            Set<Integer> followees = new HashSet<>();
            if (followMap.containsKey(userId)) {
                followees = followMap.get(userId);
            }
            followees.add(userId);
            Stack<Post> clonePosts = (Stack<Post>) posts.clone();
            while (!clonePosts.isEmpty() && feeds.size() < 10) {
                Post post = clonePosts.pop();
                if (followees.contains(post.userId)) {
                    feeds.add(post.tweetId);
                }
            }
            return feeds;
        }
        
        public void follow(int followerId, int followeeId) {
            if (followMap.containsKey(followerId)) {
                followMap.get(followerId).add(followeeId);
            } else {
                Set<Integer> followees = new HashSet<>();
                followees.add(followeeId);
                followMap.put(followerId, followees);
            }
        }
        
        public void unfollow(int followerId, int followeeId) {
            if (followMap.containsKey(followerId)) {
                followMap.get(followerId).remove(followeeId);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.