1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/* Sort elements of Java Vector Example This Java Example shows how to sort the elements of java Vector object using Collections.sort method. */ import java.util.Vector; import java.util.Collections; public class SortJavaVectorExample { public static void main(String[] args) { //create Vector object Vector v = new Vector(); //Add elements to Vector v.add("1"); v.add("3"); v.add("5"); v.add("2"); v.add("4"); /* To sort a Vector object, use Collection.sort method. This is a static method. It sorts an Vector object's elements into ascending order. */ Collections.sort(v); //display elements of Vector System.out.println("Vector elements after sorting in ascending order : "); for(int i=0; i<v.size(); i++) System.out.println(v.get(i)); } } /* Output would be Vector elements after sorting in ascending order : 1 2 3 4 5 */ |
Thanks very help full
Just an addition if you like to made it reverse
you should use
Comparator<integer> r = Collections.reverseOrder();
Collections.sort(v, r); // instead of Collections.sort(v)
Good example but notice when using String in a vector that sort wont work when you use any String bigger then “9” like “10”!
Its very helpful . lot of thanks
thanx