java - How to sort list with multiple condition? -


i have arraylist name , id.

list.add(new model2(null, "name1")); list.add(new model2("13", "name2")); list.add(new model2(null, "name1")); list.add(new model2("13", "name4")); list.add(new model2(null, "name1")); list.add(new model2("13", "name6")); 

first if id null , name

//the result should this:     //1. null , name1     //2. null , name1     //3. null , name1     //4. 13,name2     //5. 13,name4     //6. 13,name6 

i know how sort null values:

collections.sort(list,sorting());         public static comparator<? super model2> sorting() {         comparator<model2> sortedlist = new comparator<model2>() {             @override             public int compare(model2 o1, model2 o2) {                 return o1.getid() == null ? -1 : 0;             }         };         return sortedlist;     } 

but names values?

first have figure out how want compare 2 strings. should name2 come before name10, need extract number string. see here how that.

you can order strings in many different ways, i'll describe idea. in compare method, should have following instead:

public int compare(model2 o1, model2 o2) {     if (o1.getid() == null) return -1;     else if (o2.getid() == null) return 1;     else return comparestrings(o1.getname(), o2.getname()); } 

the thing have consider here how implement comparestrings method.

p.s. can of course write single return statement, thought if-statements more readable.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -