Java sort list by property of object

What you will learn here java String property sorting

  • Java sort list by property of object

Here we will see how to sort String property of class. Please follow the following steps to know how to sort list of objects by property of object in java.

Java sort list by property of object

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

public class StringSortingClass implements Comparable
{
	String name;

	public static void main(String[] args)
	{
		StringSortingClass S1=new StringSortingClass();
		StringSortingClass S2=new StringSortingClass();
		StringSortingClass S3=new StringSortingClass();
		StringSortingClass S4=new StringSortingClass();
		StringSortingClass S5=new StringSortingClass();
		
		S1.name="Sagar";
		S2.name="Prem";
		S3.name="Amar";
		S4.name="Dhanraj";
		S5.name="Rahul";
		
		List names=new ArrayList();
		names.add(S1);
		names.add(S2);
		names.add(S3);
		names.add(S4);
		names.add(S5);
		
		System.out.println("Before Sorting................................");
		for(int i=0;i<names.size();i++)
		{
			System.out.print(names.get(i).name+"	");
		}
		
		System.out.println("\n");
		System.out.println("After Sorting................................");
		Collections.sort(names);
		for(int i=0;i<names.size();i++)
		{
			System.out.print(names.get(i).name+"	");
		}
	}

	@Override
	public int compareTo(StringSortingClass o)
	{
		int a=this.name.compareTo(o.name);
		if(a>1)
			return 1;
		
		else if(a<-1)
			return -1;
		
		else
			return 0;
	}
	
}


OUTPUT

Before Sorting................................
Sagar Prem Amar Dhanraj Rahul

After Sorting................................
Amar Dhanraj Prem Sagar Rahul

You may also like...