-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocialMediaRepository.java
More file actions
68 lines (56 loc) · 1.91 KB
/
SocialMediaRepository.java
File metadata and controls
68 lines (56 loc) · 1.91 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Repository for data access
* Design Pattern: Repository Pattern
*/
public class SocialMediaRepository {
private final Map<String, User> users;
private final Map<String, Post> posts;
private final Map<String, List<String>> userPosts; // userId -> List of postIds
public SocialMediaRepository() {
this.users = new ConcurrentHashMap<>();
this.posts = new ConcurrentHashMap<>();
this.userPosts = new ConcurrentHashMap<>();
}
public void addUser(User user) {
users.put(user.getUserId(), user);
userPosts.putIfAbsent(user.getUserId(), new CopyOnWriteArrayList<>());
}
public User getUser(String userId) {
return users.get(userId);
}
public boolean userExists(String userId) {
return users.containsKey(userId);
}
public void addPost(Post post) {
posts.put(post.getPostId(), post);
List<String> postsList = userPosts.get(post.getUserId());
if (postsList != null) {
postsList.add(post.getPostId());
}
}
public Post getPost(String postId) {
return posts.get(postId);
}
public boolean postExists(String postId) {
return posts.containsKey(postId);
}
public void removePost(String postId) {
Post post = posts.remove(postId);
if (post != null) {
List<String> postsList = userPosts.get(post.getUserId());
if (postsList != null) {
postsList.remove(postId);
}
}
}
public List<String> getUserPostIds(String userId) {
return userPosts.getOrDefault(userId, new CopyOnWriteArrayList<>());
}
public Map<String, User> getAllUsers() {
return new ConcurrentHashMap<>(users);
}
}