How to Sort ArrayList of Objects in Java, Sorting ArrayList by Objects in Java


How to Sort ArrayList of Objects in Java, Sorting ArrayList by Objects in Java



In java ArrayList is a collection of Objets means when we want to store the collection of objects into a single variable the ArrayList is used.

Sorting of Integer, Float, Double, Long and String is very simple, Java provide the Collections interface to sort the list.

For Example

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

class SortArrayList
{
public static void main(String st[])
{
ArrayList<String> strlist=new ArrayList<String>();
strlist.add("Java");
strlist.add("XML");
strlist.add("AJAX");
strlist.add("SQL");
strlist.add("ASP.Net");
strlist.add("JavaScript");

System.out.println("UnSorted List");
for(String str:strlist)
  System.out.println(str);

Collections.sort(strlist);

System.out.println("Sorted List");

for(String str:strlist)
  System.out.println(str);
}
}

Output

UnSorted List
Java
XML
AJAX
SQL
ASP.Net
JavaScript

Sorted List
AJAX
ASP.Net
Java
JavaScript
SQL

XML

But if you want to Sort the ArrayList for those objects which does not has the countable values like TextFiled, Button etc.
Then there is no method in java to sort such ArrayList but you can Sort it by apply some logic which i am provided to you.

Example to Sort the ArrayList for TextField

import javax.swing.*;
import java.awt.*;
import java.io.*;

import java.util.*;

class SortArrayList extends JFrame
{
public static void main(String st[])
{
ArrayList<TextField> newBox=new ArrayList<TextField>();
int yVal=80;
public SortArrayList()
{
this.setSize(600,500);
this.setVisible(true);

this.setLayout(null);
this.setTitle("Sorting ArrayList for TextFields");
for(int i=0;i<5;i++)
{
TextField t=new TextField();
yVal+=60;
t.setBounds(xVal, yVal,75,50);
add(t);

newBox.add(t);

sortArrayList();
}
public void sortArrayList()
{
TextField[] temp=newBox.toArray(new TextField[newBox.size()]);
for(int i=0;i<temp.length;i++)
{
for(int j=0;j<temp.length;j++)
{
if(Integer.parseInt(temp[i].getText())<Integer.parseInt(temp[j].getText()))
{
TextField tmp=temp[i];
temp[i]=temp[j];
temp[j]=tmp;
}
}

}
for(int i=0;i<5;i++)
  newBox.remove(i);
for(int i=0;i<5;i++)
  newBox.add(temp[i]);
for(int i=0;i<5;i++)
System.out.println(newBox.get(i).getText());
}

}
}

The Above Example is a sample example for Sorting the TextField by value and you can sort any object with this logic.


Please Give your valueable Comments
Thanks & Regards
Talib Hassan

{ 0 comments... read them below or add one }

Post a Comment