java - Sorting contents of attachments in numerical form in arraylist -
i trying non-transformed files in /attachments folder , put in array , sort non-transformed attachment array alphanumerically using java. here code
// non-transformed files in /attachments folder , put in array file f = new file("d:\\template_export\\template\\attachments"); arraylist<string> attachmentfiles = new arraylist<string>(arrays.aslist(f.list())); system.out.println("attachmentfiles :" + attachmentfiles);
and need sort following output:
attachmentfiles :[0.gif, 1.gif, 10.gif, 11.gif, 12.gif, 13.gif, 14.gif, 15.gif, 16.gif, 17.gif, 18.gif, 19.gif, 2.gif, 20.gif, 21.gif, 22.gif, 23.gif, 24.gif, 25.gif, 26.gif, 27.gif, 28.gif, 29.gif, 3.gif, 30.html, 31.messages, 32.messages, 4.gif, 5.gif, 6.gif, 7.gif, 8.gif, 9.gif]
i tried below code:
collections.sort(attachmentfiles); for(string counter: attachmentfiles){ system.out.println(counter); }
but it's not getting sorted.
to compare 2 strings of digits of different length if numbers necessary left fill shortest string 0 chars.
so first necessary search first point in both strings. compare positions , fill 0 "shortest" number zeros in following code.
collections.sort(attachmentfiles,new comparator<string>() { public int compare(string o1, string o2) { int point1 = o1.indexof('.'); // if no point present assume present last position if (point1 == -1) { point1 = o1.length(); } int point2 = o2.indexof('.'); // if no point present assume present last position if (point2 == -1) { point2 = o2.length(); } if (point1 > point2) { char[] chars = new char[point1-point2]; arrays.fill(chars, '0'); o2 = new string(chars) + o2; } else if (point1 < point2) { char[] chars = new char[point2-point1]; arrays.fill(chars, '0'); o1 = new string(chars) + o1; } return o1.compareto(o2); } });
Comments
Post a Comment