java - Create multiple lists dynamically -
java version "1.7.0_45"
i trying create mutliple lists contain same messages sent jid.
for example offlinemessageheaderlist contain many messages different , same jid's. want group ones have same jids in there own lists.
messagelist1 -> messages john messagelist2 -> messages peter etc.
then @ end check ones empty , add them grouplist.
however, solution not declare first , have more or less messages same jid.
code snippet checking , adding
list<list<messageheader>> grouplist = new arraylist<>(); list<messageheader> messagelist1 = new arraylist<>(); list<messageheader> messagelist2 = new arraylist<>(); list<messageheader> messagelist3 = new arraylist<>(); list<messageheader> messagelist4 = new arraylist<>(); if(offlinemessageheaderlist.size() > 0) { for(offlinemessageheader header : offlinemessageheaderlist) { log.log(level.info, "jid: " + header.getjid()); log.log(level.info, "stamp: " + header.getstamp()); log.log(level.info, "user: " + header.getuser()); messageheader messageheader = new messageheader(header.getjid(), header.getstamp(), header.getuser()); /* check have message list jid */ /* messagelist1 have jid message */ if(messagelist1.get(0).getjid().compareto(messageheader.getjid()) == 0) { /* add same jid list */ messagelist1.add(messageheader); } else { /* jid different need add new list */ if(messagelist2.get(0).getjid().compareto(messageheader.getjid()) == 0) { messagelist2.add(messageheader); } } /* same others */ } /* add non-empty lists grouplist */ if(!messagelist1.isempty()) { grouplist.add(messagelist1); } if(!messagelist2.isempty()) { grouplist.add(messagelist2); } if(!messagelist3.isempty()) { grouplist.add(messagelist3); } if(!messagelist4.isempty()) { grouplist.add(messagelist4); } } class of messageheader public class messageheader { private string mjid; private string mstamp; private string muser; public messageheader(string jid, string stamp, string user) { mjid = jid; mstamp = stamp; muser = user; } public string getjid() { return mjid; } public string getstamp() { return mstamp; } public string getuser() { return muser; } }
is there way can in more dynamic way?
if understood correctly, can use below approach minimize number of objects , proper use of data structure.
1) create map<string, list<messageheader>>
store message each jid. in map key jid , value list of messages jid.
2) when message comes, check if key jid present:
if yes - fetch value map jid, return
list<messageheader>
object , add new message list.if no - create new entry within map, jid key , new
arraylist<messageheader>
later iterate through map eligible jid inserting group list
Comments
Post a Comment