How to sort primitive data in the list

How to sort primitive data in the list

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.

 

 

Leave a Reply