How to sort primitive data in the list
Table of Contents
There is a list having primitive data, then how to sort the data in the list.
List – Integer Data Type
ListIntegerSorting.java
package com.narayanatutorial.primitive.sorting; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListIntegerSorting { public static void main(String args[]) { List<Integer> list = new ArrayList<Integer>(); list.add(123); list.add(34); list.add(567); System.out.println("****Before Sorting****"); list.stream().forEach(name -> System.out.println(name)); Collections.sort(list); System.out.println("****After Sorting****"); list.stream().forEach(name -> System.out.println(name)); list.clear(); list = new ArrayList<Integer>(); list.add(123); list.add(34); list.add(567); //sorting using stream System.out.println("**** Sorting using list stream ****"); list.stream().sorted().forEach(value->System.out.println(value)); } }
Output
****Before Sorting**** 123 34 567 ****After Sorting**** 34 123 567 **** Sorting using list stream **** 34 123 567
List – String Data Type
ListStringSorting.java
package com.narayanatutorial.primitive.sorting; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListStringSorting { public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add("Tutorial"); list.add("Narayana"); list.add("Swamy"); System.out.println("****Before Sorting****"); list.stream().forEach(name -> System.out.println(name)); Collections.sort(list); System.out.println("****After Sorting****"); list.stream().forEach(name -> System.out.println(name)); list.clear(); list = new ArrayList<String>(); list.add("Tutorial"); list.add("Narayana"); list.add("Swamy"); // sorting using stream System.out.println("**** Sorting using list stream ****"); list.stream().sorted().forEach(value -> System.out.println(value)); } }
Output
****Before Sorting**** Tutorial Narayana Swamy ****After Sorting**** Narayana Swamy Tutorial **** Sorting using list stream **** Narayana Swamy Tutorial
Get full source code from Git.
Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in the IT industry for more than 12 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting, Website Development, and IAM(ForgeRock) Specialist
I am a self-learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.