Hi, I want to sort elements from the collection in java. Can anyone help me to do this? If you have the program to achieve this, then please forward that to me. I am waiting for your reply. Please help me to achieve this.
Hi, I want to sort elements from the collection in java. Can anyone help me to do this? If you have the program to achieve this, then please forward that to me. I am waiting for your reply. Please help me to achieve this.
Hi, I have think about the sorting elements of collection, but not find any solution about this. I know how to sort array in java. If you able to get this information then please give it to me also. I am giving you the code to sort array:
Code:import java.util.ArrayList; import java.util.Collections; public class SortJavaArrayListExample { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); arrayList.add("1"); arrayList.add("3"); arrayList.add("5"); arrayList.add("2"); arrayList.add("4"); Collections.sort(arrayList); System.out.println("ArrayList elements after sorting in ascending order : "); for(int i=0; i<arrayList.size(); i++) System.out.println(arrayList.get(i)); } }
Hi, I am sending you the code which will sort elements of java vector in the ascending order. Just make use of it. It will help you to sort elements.
Output would beCode:import java.util.Vector; import java.util.Collections; public class SortJavaVectorExample { public static void main(String[] args) { Vector v1= new Vector(); v1.add("1"); v1.add("3"); v1.add("5"); v1.add("2"); v1.add("4"); Collections.sort(v); System.out.println("Vector elements after sorting in ascending order : "); for(int i=0; i<v1.size(); i++) System.out.println(v1.get(i)); } }
Vector elements after sorting in ascending order :
1
2
3
4
5
HI, use the following code which will help you to sort the elements of collection. Collections.sort(list) method sorts all the elements of the specified Collection. List of the elements which have to be sorted are passed through the method as a parameter. This method sorts elements in ascending order by default.
Code:import java.util.*; import java.io.*; public class sortcoll { public static void main(String[] args) throws IOException { int num = 0; BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("How many elements you want to enter in the list : "); try{ num = Integer.parseInt(bf.readLine()); } catch(NumberFormatException ne){ System.out.println(ne.getMessage() + " is not a legal entry."); System.out.println("Please enter a numeric value."); System.exit(1); } String[] names = new String[num]; System.out.println("Please enter some names : "); for(int i = 0; i < num; i++){ names[i] = bf.readLine(); } List<String> list = Arrays.asList(names); Collections.sort(list); System.out.print("Elements of the list in sorted order : " + list); } }
Bookmarks