下面是一个示例代码,演示了如何按照ID分组并像WhatsApp一样显示通知:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NotificationManager {
private Map> notificationMap;
public NotificationManager() {
notificationMap = new HashMap<>();
}
public void showNotification(String id, String message) {
if (notificationMap.containsKey(id)) {
notificationMap.get(id).add(message);
} else {
List messages = new ArrayList<>();
messages.add(message);
notificationMap.put(id, messages);
}
displayNotification();
}
public void displayNotification() {
for (String id : notificationMap.keySet()) {
List messages = notificationMap.get(id);
System.out.println("New Notifications for ID: " + id);
for (String message : messages) {
System.out.println(message);
}
System.out.println();
}
}
public static void main(String[] args) {
NotificationManager manager = new NotificationManager();
manager.showNotification("001", "New message from John");
manager.showNotification("002", "New message from Jane");
manager.showNotification("001", "New message from Mike");
manager.showNotification("003", "New message from Alice");
// Output:
// New Notifications for ID: 001
// New message from John
// New message from Mike
//
// New Notifications for ID: 002
// New message from Jane
//
// New Notifications for ID: 003
// New message from Alice
}
}
在上面的示例代码中,我们使用了一个Map
来存储按ID分组的通知消息。showNotification
方法用于将新的通知消息添加到对应的ID分组中,并调用displayNotification
方法来显示所有通知。displayNotification
方法遍历notificationMap
中的每个ID,然后按照WhatsApp的样式显示通知消息。
在main
方法中,我们模拟了几个通知消息的添加,并通过调用showNotification
方法来显示通知。最后,我们通过调用displayNotification
方法来打印出所有通知。
注意:上述代码只是一个简单的示例,实际开发中可能需要更复杂的逻辑来管理和显示通知。