{"id":78994,"date":"2020-06-10T09:00:44","date_gmt":"2020-06-10T03:30:44","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=78994"},"modified":"2020-06-10T09:00:44","modified_gmt":"2020-06-10T03:30:44","slug":"how-to-sort-a-list-in-java","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/","title":{"rendered":"Collections.sort() &#8211; Ways to Sort a List in Java"},"content":{"rendered":"<p>In our previous article, we have discussed all the methods of the List in Java Programming Language. Now in this article, we are going to discuss the methods to sort the List elements in Java Programming Language like Collections.sort().<\/p>\n<p>In Java Programming Language, the List provides the functionality to the developer to store the duplicate and multiple null values in a single List. The real-time programming paradigm List also provides the functionality of traversing the list in both directions.<\/p>\n<p>Sometimes the programmer needs to store the list before processing its elements. Let\u2019s discover how we can sort the elements of a list in Java.<\/p>\n<h3>What is a Java List?<\/h3>\n<p>The List is the subinterface of the Collections interface. List interface imported from <strong>Java.util.List<\/strong> as the child interface of Collections.<\/p>\n<p>A List is the ordered collection of objects i.e. in the list the order of the elements is maintained. It also supports having duplicate values in it.<\/p>\n<p>In this article, we will implement some methods of List and Sort the ArrayList.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/sort-list-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-79040\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/sort-list-in-java.jpg\" alt=\"sort list in java\" width=\"643\" height=\"368\" \/><\/a><\/p>\n<h3>Collections.sort() method in Java<\/h3>\n<p>To sort the list in Java we have to understand the working of the Collections.sort() method which is present in <strong>java.util.Collections<\/strong> class.<\/p>\n<p>The java.Collections.sort() is very similar to the java.util.Arrays.sort() method; rather it is much better than it. The java.Collections.sort() method is also used to sort the linked list, array, queue, and other data structures.<\/p>\n<p>If we talk about the working of this method, then the method works on ASCII values. The java.Collections.sort() method sorts the list elements by comparing the ASCII values of the elements.<\/p>\n<p>The method compares the first element by its ASCII values, if it matches then it compares the second element and so on.<\/p>\n<p><strong>Code to sort the list in ascending order with Collections.sort() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.listsort;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ListSort_Java \/\/Class for sorting the List in Java\n{\n  public static void main(String[] args) {\n    List &lt; String &gt; myList = new ArrayList &lt; String &gt; ();\n    myList.add(\"W\");\n    myList.add(\"T\");\n    myList.add(\"A\");\n    myList.add(\"G\");\n    myList.add(\"I\");\n    myList.add(\"B\");\n    myList.add(\"Z\");\n    myList.add(\"0\");\n    myList.add(\"U\");\n    myList.add(\"7\");\n\n    System.out.println(\"The unsorted List is:\");\n\n    for (String myStr: myList) {\n      System.out.print(\" \" + myStr);\n    }\n\n    \/\/Collections.sort() are used to sort the List\n    Collections.sort(myList);\n\n    System.out.println(\"\\nThe Sorted List is\");\n\n    for (String myStr: myList) {\n      System.out.print(\" \" + myStr);\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">The unsorted List is:<br \/>\nW T A G I B Z 0 U 7<br \/>\nThe Sorted List is:<br \/>\n0 7 A B G I T U W Z<\/div>\n<h3>Collections.reverseOrder() Method in Java<\/h3>\n<p>To sort the list in reverse order, we have to discuss the reverseOrder() method which is also present in the class Collections.reverseOrder().<\/p>\n<p>The working of this method is very similar to the Collections.sort() method but unlike the Collections.sort() method, it sorts the list elements in reverse order of the natural ordering on the collections of objects.<\/p>\n<p>The method compares the elements according to the ASCII values and arranges them in reverse order.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.listsort;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ListSort_Java \/\/Class for sorting the List in Java\n{\n  public static void main(String[] args) {\n    List &lt; String &gt; myList = new ArrayList &lt; String &gt; ();\n    myList.add(\"W\");\n    myList.add(\"T\");\n    myList.add(\"A\");\n    myList.add(\"G\");\n    myList.add(\"I\");\n    myList.add(\"B\");\n    myList.add(\"Z\");\n    myList.add(\"0\");\n    myList.add(\"U\");\n    myList.add(\"7\");\n\n    System.out.println(\"The unsorted List is:\");\n\n    for (String myStr: myList) {\n      System.out.print(\" \" + myStr);\n    }\n\n    \/\/Collections.sort() are used to sort the List\n    Collections.sort(myList, Collections.reverseOrder());\n    System.out.println(\"\\nThe Sorted List in reverse order is:\");\n    for (String myStr: myList) {\n      System.out.print(\" \" + myStr);\n    }\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nThe unsorted List is:<br \/>\nW T A G I B Z 0 U 7<br \/>\nThe Sorted List in reverse order is:<br \/>\nZ W U T I G B A 7 0<\/p>\n<h3>The sorted() Method in Java<\/h3>\n<p>Another way to sort the list is by <strong>Stream<\/strong> class which is present in the java.util package.<\/p>\n<p>The stream class provides a method named as sorted() which sorts the list in natural order by comparing ASCII values as we discussed in the previous section. The sorted() method used to sort the list of objects or collections of the objects in the ascending order.<\/p>\n<p>If the collections of the objects are comparable then it compares and returns the sorted collections of objects; otherwise it throws an exception from java.lang.ClassCastException.<\/p>\n<p><strong>Code to Sort elements of the list alphabetically with the sorted() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.listsort;\nimport java.util. * ;\nimport java.util.stream. * ;\n\npublic class ListSort_Java \/\/ Class for sorting the List in Java\n{\n  public static void main(String[] args) {\n    List &lt; String &gt; myList = Arrays.asList(\"Joy\", \"Alice\", \"Bob\", \"Max\", \"Charles\", \"Katty\");\n    System.out.println(\"Sorted List is: \");\n    List &lt; String &gt; sortList = myList.stream().sorted().collect(Collectors.toList());\n    sortList.forEach(System.out::println);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nSorted List is:<br \/>\nAlice<br \/>\nBob<br \/>\nCharles<br \/>\nJoy<br \/>\nKatty<br \/>\nMax<\/p>\n<h3>Comparator.reverseOrder() Method in Java<\/h3>\n<p>For reverse order sorting with the help of sorted() method, we have to use another method named Comparator.reverseOrder().<\/p>\n<p>The reverseOrder() method is declared in the Comparator Interface of Java which defines in the java.util package.<\/p>\n<p>The method sorted() returns the collection of objects in a sorted manner and after that, we apply Comparator.reverseOrder() method that converts the sorted objects into the reverse natural ordering.<\/p>\n<p>When we try to compare Null with the help of Comparator Interface it throws the NullPointerException.<\/p>\n<p><strong>Code to Sort elements of the list alphabetically in reverse order with the sorted() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">ackage com.techvidvan.listsort;\nimport java.util. * ;\nimport java.util.stream.Collectors;\n\npublic class ListSort_Java_Reverse \/\/ Class for sorting the List in Reverse Order in Java\n{\n  public static void main(String[] args) {\n    List &lt; String &gt; myList = Arrays.asList(\"Joy\", \"Alice\", \"Bob\", \"Max\", \"Charles\", \"Katty\");\n    System.out.println(\"Sorted List in Reverse Order is: \");\n    List &lt; String &gt; sortList = myList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());\n    sortList.forEach(System.out::println);\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><br \/>\nSorted List in Reverse Order is:<br \/>\nMax<br \/>\nKatty<br \/>\nJoy<br \/>\nCharles<br \/>\nBob<br \/>\nAlice<\/p>\n<h3>Comparator.naturalOrder() Method in Java<\/h3>\n<p>The Comparator.naturalOrder() method is used to compare the Comparable objects in natural order(ascending order). The Comparator that is returned as a result of the comparison is Serializable.<\/p>\n<p>When we compare null with objects, this method throws a NullPointerException. This method is available from Java 8.<\/p>\n<p><strong>Syntax of Comprator.naturalOrder() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">static &lt; T extends Comparable &lt; ?super T &gt;&gt; Comparator &lt; T &gt; naturaOrder()<\/pre>\n<p>Where T is the Element of Comparable type that is to be compared.<\/p>\n<p><strong>Code to sort elements in natural order using the Comparator.naturalOrder() method:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.listsort;\nimport java.util. * ;\npublic class NaturalOrderDemo {\n  public static void main(String[] args) {\n    List &lt; String &gt; countryNames = Arrays.asList(\"Nepal\", \"India\", \"Italy\", \"Japan\", \"\", \"Bhutan\");\n    List &lt; String &gt; countryNames1 = Arrays.asList(\"Nepal\", \"india\", \"China\", \"Japan\", \"\", \"bhutan\");\n    System.out.println(countryNames);\n    countryNames.sort(String.CASE_INSENSITIVE_ORDER);\n    System.out.println(countryNames1);\n    countryNames.sort(Comparator.naturalOrder());\n    System.out.println(countryNames);\n    countryNames1.sort(Comparator.naturalOrder());\n    System.out.println(countryNames1);\n  }\n}\n<\/pre>\n<p><strong>Output:<\/strong><br \/>\n[Nepal, India, Italy, Japan, , Bhutan]<br \/>\n[Nepal, india, China, Japan, , bhutan]<br \/>\n[, Bhutan, India, Italy, Japan, Nepal]<br \/>\n[, China, Japan, Nepal, bhutan, India]<\/p>\n<h3>Conclusion<\/h3>\n<p>In this article, we learned to sort the list element with the help of many methods like collections.sort(). We implemented each method with the help of Java programs.<\/p>\n<p>Then we also sorted the elements in the reverse order. We hope, now you can easily learn to sort the list elements in either ascending or descending order.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In our previous article, we have discussed all the methods of the List in Java Programming Language. Now in this article, we are going to discuss the methods to sort the List elements in&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":79041,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[2803,2804],"class_list":["post-78994","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-collections-sort","tag-sort-a-list-in-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Collections.sort() - Ways to Sort a List in Java - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn ways to sort list in java using methods - collections.sort(),Collections.reverseOrder(), sorted(),Comparator.reverseOrder(),Comparator.naturalOrder()\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Collections.sort() - Ways to Sort a List in Java - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn ways to sort list in java using methods - collections.sort(),Collections.reverseOrder(), sorted(),Comparator.reverseOrder(),Comparator.naturalOrder()\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-06-10T03:30:44+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Java-List-Sort.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Collections.sort() - Ways to Sort a List in Java - TechVidvan","description":"Learn ways to sort list in java using methods - collections.sort(),Collections.reverseOrder(), sorted(),Comparator.reverseOrder(),Comparator.naturalOrder()","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Collections.sort() - Ways to Sort a List in Java - TechVidvan","og_description":"Learn ways to sort list in java using methods - collections.sort(),Collections.reverseOrder(), sorted(),Comparator.reverseOrder(),Comparator.naturalOrder()","og_url":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-06-10T03:30:44+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Java-List-Sort.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Collections.sort() &#8211; Ways to Sort a List in Java","datePublished":"2020-06-10T03:30:44+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/"},"wordCount":849,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Java-List-Sort.jpg","keywords":["Collections.sort()","sort a list in java"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/","url":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/","name":"Collections.sort() - Ways to Sort a List in Java - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Java-List-Sort.jpg","datePublished":"2020-06-10T03:30:44+00:00","description":"Learn ways to sort list in java using methods - collections.sort(),Collections.reverseOrder(), sorted(),Comparator.reverseOrder(),Comparator.naturalOrder()","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Java-List-Sort.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Java-List-Sort.jpg","width":802,"height":420,"caption":"collections.sort()"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/how-to-sort-a-list-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Collections.sort() &#8211; Ways to Sort a List in Java"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78994","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=78994"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78994\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/79041"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=78994"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=78994"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=78994"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}