2

I have an List of Messages objects. My message object consist of sender and CaseNumber. A SQL query is pulls all the messages into a list. In this list I have multiple of the same CaseNumber.
What I would like to accomplish is loop though the current Messages List and split them out into their own individual list based on the CaseNumber.

I've fiddled around but I am not sure how to accomplish this within the for loop.

    public class Messages {
    private String sender = "";
    private int caseNumber = 0

     public int getCaseNumber() {
    return caseNumber;
}
    public void setCaseNumber(int caseNumber) {
        this.caseNumber = caseNumber;
    }

    public String getSender() {
      return sender;
    }
    public void setSender(String sender) {
    this.sender = sender;
    }
    
   }

SQL makes a call and maps the vars into a huge object.
  public List<Messages> getAllMessages()
  {
   List<Messages> entries = null;
   String sql = "select sender, caseNumber from Messages";
   entries = jdbcTemplate.query(sql, new MessagesMapper());
   return entries;
  }

//for loop in my function.
for(Messages m : allMessages)
{
    //This is the part i am stumped on how to I check if case number = case number if so create a new Messages List. Then if any of the additional cases in the list, add them to this new List.  If it's a new caseNumber, create a new list.
}

I thought about changing the sql call just to pull each messages by caseNumber but I feel that I could just be hammering SQL which doesn't feel efficient.

Hopfully this makes sense on what i want to accomplish. Split List of objects bases on caseNumber and create it's own List of that object.

1
  • You could use a map and the CaseNumber is the key. The value part would then be a list of senders.
    – Twistleton
    Commented Oct 17, 2023 at 16:09

3 Answers 3

3

You can use java stream api to group the list.

Map<Integer, List<Message>> groupedMessages = allMessages.stream().collect(Collectors.groupingBy(Message::getCaseNumber));
0
1

You could create a Map<Integer, List<String>> object like

Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();

and inside the for cycle, check whether the given number exists in the map and if not, create it:

if (!map.containsKey(caseNumber)) {
    map.put(caseNumber, new ArrayList<String>());
}
map.get(caseNumber).add(sender);
0

Create a Map, where the key is caseNumber, and the value is a List of Messages objects.

Map<Integer, List<Messages>> map = new TreeMap<>();
for (Messages m : getAllMessages())
    if (map.containsKey(m.caseNumber)) map.get(m.caseNumber).add(m);
    else map.put(m.caseNumber, new ArrayList<>(List.of(m)));

Not the answer you're looking for? Browse other questions tagged or ask your own question.