How to sort a List via Java
Posted On
Posted By admin
In this blog post, I will be explaining how you can sort a list via Java. Consider the following code snippet:
package learnjava.collections; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortDemo { public static void main(String[] args) { List<Integer> input = new ArrayList<Integer>(); input.add(3); input.add(9); input.add(5); input.add(15); input.add(11); System.out.println("Before sorting:"+input); Collections.sort(input); System.out.println("Before sorting:"+input); } }
This code uses the Collections.sort method. The Collections class contains static utility methods that operate on collections like List, Set etc. When the Collections.sort method is invoked, it sorts the input list in ascending order. The return type of this method is void, so the input list is modified for sort. This code will print the following output:
Before sorting:[3, 9, 5, 15, 11] Before sorting:[3, 5, 9, 11, 15]
If you like this post, please do let me know via the comments box below. You can also connect with me via my Facebook Page or subscribe to my Youtube channel!