Search code examples
javaobjectarraylistsplit

Split an List of objects based caseNumber into a new List of objects


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.


Solution

  • You can use java stream api to group the list.

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