How to sort list in java

What you will learn here about Sorting in java

  • How to sort list in java or how to sort arraylist in java
  • How to sort list in descending order in java

How to sort list in java

Sample program to know how to sort list in java or how to sort arraylist in java is given below

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ArrayListSorting 
{
	public static void main(String[] args) 
	{
		List list=new ArrayList();
		list.add(-10);
		list.add(130);
		list.add(205);
		list.add(100);
		
		System.out.println("Before Sorting ->"+list);
		List Sortedlist=list.stream().sorted().collect(Collectors.toList());
		System.out.println("After Sorted  ->"+Sortedlist);
		
	}
}

OUTPUT

Before Sorting ->[-10, 130, 205, 100]
After Sorted ->[-10, 100, 130, 205]

How to sort list in descending order in java

Sample program to know how to sort list in descending order in java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ListRemoveDuplicates 
{
	public static void main(String[] args) 
	{
		List list=new ArrayList();
		list.add(-10);
		list.add(130);
		list.add(205);
		list.add(100);
		
		System.out.println("Before Sorting ->"+list);
		List Sortedlist=list.stream().sorted().collect(Collectors.toList());
		Collections.reverse(Sortedlist);	
		
		System.out.println("Sorted in reverse order ->"+Sortedlist);
	}
}

OUTPUT

Before Sorting ->[-10, 130, 205, 100]
Sorted in reverse order ->[205, 130, 100, -10]

You may also like...