Friday 15 May 2015

java - How to generate list object into multiple list base on a object property? -



java - How to generate list object into multiple list base on a object property? -

this object

public static class phone{ public string model; public string imei; public string date_active; }

this list object example

phone = new phone ("qs17", "1122", "20/10/2014"); phone b = new phone ("qs18", "4345", "20/10/2014"); phone c = new phone ("qs19", "3451", "21/10/2014"); phone d = new phone ("qs20", "6756", "22/10/2014"); phone e = new phone ("qs17", "1257", "22/10/2014"); phone f = new phone ("qs17", "9077", "22/10/2014"); list.add(a); list.add(b); list.add(c); list.add(d); list.add(e); list.add(f);

i want split list multiple list has same date. example:

list1 = [{"qs17","1122","20/10/2014"}, {"qs18","4345","20/10/2014"}] list2 = [{"qs19","3451","21/10/2014"}] list3 = [{"qs20","6756","22/10/2014"}, {"qs17","1257","22/10/2014"}, {"qs17","9077","22/10/2014"}]

i seach way on web, , found this

static <t> list<list<t>> chopped(list<t> list, final int l) { list<list<t>> parts = new arraylist<list<t>>(); final int n = list.size(); (int = 0; < n; += l) { parts.add(new arraylist<t>( list.sublist(i, math.min(n, + l))) ); } homecoming parts;

}

but seem depend on specific number sublist, not base of operations on property of object.

i search find way, , found this

map<yoursplitterproperty, list<youritem>> map = new hashmap<yoursplitterproperty, list<youritem>(); (youritem item : youritems) { list<youritem> list = map.get(item.getsplitterproperty()); if (list == null) { list = new arraylist<youritem>(); map.put(item.getsplitterproperty(), list); } list.add(item); }

but way homecoming list, need homecoming multiple list have same property on root list.

may help me ?

the first method split list<t> in smaller lists of same size. sec method split list smaller lists based on value of field stored in elements of list. result shown in method, you're looking sec method changes:

return list<t> list<list<t>> rather map<key, list<t>. the returned list<list<t>> should sorted.

you can accomplish using treemap map implementation. modifications you're looking for:

public static list<list<phone>> splitbydateactive(list<phone> phonelist) { map<string, list<phone>> map = new treemap<string, list<phone>(); (phone phone : phonelist) { list<phone> list = map.get(phone.getdate_active()); if (list == null) { list = new arraylist<phone>(); map.put(phone.getdate_active(), list); } list.add(phone); } list<list<phone>> phonelistsplitted = new arraylist<list<phone>>(); (list<phone> phonelistvar : map.values()) { phonelistsplitted.addall(phonelistvar); } homecoming phonelistsplitted; }

java android

No comments:

Post a Comment