Home > Back-end >  Java remove dupplicate attribute in List<Message>
Java remove dupplicate attribute in List<Message>

Time:02-16

I have list of message, class Message have 2 attribute:
The following code below:

class Message{
    String message;
    long time;
}
List<Message> listMessage = new ArrayList<>();
list.add("A", 1);
list.add("A", 2);
list.add("B", 1);
list.add("C", 1);
list.add("C", 2);

I want to remove duplicate message from list but must keep the message with the longest time in List
Input

("A", 1), ("A", 2), ("B", 1), ("C", 1), ("C", 2)


Expect result

("A", 2), ("B", 1), ("C", 2)

CodePudding user response:

static class Message {
    String message;
    long time;
    
    public Message(String message, long time) {
        this.message = message;
        this.time = time;
    }
}

public static void putLatestMessage(Map<String, Message> messageMap, Message message) {
    if (messageMap.containsKey(message.message) && messageMap.get(message.message).time >= message.time) {
        return;
    } else {
        messageMap.put(message.message, message);
    }
}

public static void main(String[] args) {
    Map<String, Message> messageMap = new HashMap<>();
    putLatestMessage(messageMap, new Message("A", 1));
    putLatestMessage(messageMap, new Message("B", 2));
    putLatestMessage(messageMap, new Message("A", 2));
    putLatestMessage(messageMap, new Message("C", 2));
    putLatestMessage(messageMap, new Message("D", 1));
}

This will solve your issue.

P.S - plz go through basic data structures available in Java and their use cases.

  • Related