Java Class Object Sorting and Group -
i want sort list of classvo object follows,
classvo parameters -> id, code
sample data:
id code a1 a1,aa1 b1 b1,bb1 c1 c1,cc1 d1 d1,dd1 b1 b2,bb2 a1 a2,aa2 c1 c2,cc2 d1 d2,dd2
in classvo list objects above sample data added in unsorted way. forexample, list-1 contains b1, list-1 contains d1, list-1 contains a1, list-1 contains c1. order vary each time.
now want sort classvo list objects above. ie, before sorting records, want group in such order (first want group a1's code, b1's code, c1's code , d1's code - while grouping code should in ascending order). after grouping want classvo list object a1,b1,c1,d1.
edit:
i pasting code here
public static void main(string[] args) { list<testvo> vos = new arraylist<testvo>(); testvo testvo1 = new testvo(); testvo1.setcode("b"); testvo1.setid("b_nit_dept"); vos.add(testvo1); testvo testvo2 = new testvo(); testvo2.setid("c_nit_func"); testvo2.setcode("nit3"); vos.add(testvo2); testvo testvo4 = new testvo(); testvo4.setcode("nit4d"); testvo4.setid("d_nit_dept"); vos.add(testvo4); testvo testvo = new testvo(); testvo.setcode("nit1"); testvo.setid("a_nit"); vos.add(testvo); testvo testvo3 = new testvo(); testvo3.setcode("a"); testvo3.setid("b_nit_dept"); vos.add(testvo3); collections.sort(vos, new mycomparable()); (testvo obj: vos) { system.out.println(obj.getid()); system.out.println(obj.getcode()); } } public class mycomparable implements comparator<testvo>{ @override public int compare(testvo vo1, testvo vo2) { int ret = 0; if(vo1.getid().compareto(vo2.getid()) != 0){ ret = vo1.getid().compareto(vo2.getid()); } return ret; } }
my output is:
identifier=a_nit code=nit1 identifier=b_nit_dept code=b identifier=b_nit_dept code=a identifier=c_nit_func code=nit3 identifier=d_nit_dept code=nit4d
but expected output :
identifier=a_nit code=nit1 identifier=b_nit_dept code=a identifier=b_nit_dept code=b identifier=c_nit_func code=nit3 identifier=d_nit_dept code=nit4d
i want make output given in expected output section
you can either using java comparable or comparator. if using java 8 don't need implement compare or compareto methods in separate class. can use lambda expressions this.
collections.sort(listofclassvo , (classvo vo1, classvo vo2) -> vo1.getid().compareto(vo2.getid()));
thanks
Comments
Post a Comment