Java/Android - Two Collections.sort combined (first by int, then by name) -
i have list own objects, called orderedproducts. want sort list first int sequence
, , string name
.
i know how sort sequence first, using following default collections.sort:
collections.sort(orderedproductslist, new comparator<orderedproduct>(){ @override public int compare(orderedproduct op1, orderedproduct op2){ if(op1.getsequence() < op2.getsequence()) return -1; else if(op1.getsequence() > op2.getsequence()) return 1; else // op1.getsequence() == op2.getsequence() return 0; } });
what want sort name within ordered sequence. so, example, i've got following orderedproducts in list:
- sequence = 2; name = "aaa";
- sequence = 4; name = "aaa";
- sequence = 7; name = "bbb";
- sequence = 2; name = "ccc";
- sequence = 1; name = "zzz";
- sequence = 4; name = "zzz";
- sequence = 4; name = "abc";
this should sorted like:
5, 1, 4, 2, 7, 6, 3. sequence name 1 "zzz" 2 "aaa" 2 "ccc" 4 "aaa" 4 "abc" 4 "zzz" 7 "bbb"
in comparator, when sequence equal compare name
collections.sort(orderedproductslist, new comparator<orderedproduct>(){ @override public int compare(orderedproduct op1, orderedproduct op2){ if(op1.getsequence() < op2.getsequence()) return -1; else if(op1.getsequence() > op2.getsequence()) return 1; else return op1.getname().comparetoignorecase(op2.getname()); } });
Comments
Post a Comment