java - Sorting String objects -


i'm trying see if there easy way sort list of string objects. problem i'm facing right collections.sort(...) method not working me.

this original list, requirement purposes sorted:

    list<string> values = new arraylist<string>();       values.add("section_1");     values.add("section_2");     values.add("section_3");     values.add("section_4");     values.add("section_5");     values.add("section_6");     values.add("section_7");     values.add("section_8");     values.add("section_9");     values.add("section_10");     values.add("section_11");     values.add("section_12");     values.add("section_13"); 

and after doing collections.sort(values), order broken:

section_1 section_10 section_11  section_12 section_13 section_2 section_3 section_4 section_5 section_6 section_7 section_8 section_9 

is behavior because of lexicographical ordering used in collections.sort(...) ? there easier way make sort work way want to?

thanks in advance.

you'll need use custom comparator extracts numerical part of strings, transform them integer instances, , compare integers:

public class sectioncomparator implements comparator<string>() {     @override     public int compare(string s1, string s2) {         integer i1 = integer.valueof(s1.substring(s1.indexof('_') + 1));         integer i2 = integer.valueof(s1.substring(s2.indexof('_') + 1));         return i1.compareto(i2),     } } 

but instead of using strings represent sections, use section objects, have number attribute, tostring() method, , natural ordering using number attribute.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -