Header Ad

Monday, April 2, 2012

Java ArrayList - Sorting List of Objects in Java

We can sort list of Objects in java using Comparators and Comparable. What are these?

Comparable is an interface that is implemented by a class of Object that have to be sorted.

java.lang.Comparable: int CompareTo(Object obj1)
This method will compare this object with obj1 object. Returns int value as follows.

1. positive - this object is greater than obj1
2. zero - this object equals to obj1
3. negative - this object is smaller than obj1

Comparator : Comparator is mainly used to override compare. Comparable will provide an ability to sort of any type of Collection.

java.util.Comparator: int compare(Object o1, Objecto2) This method compares o1 and o2 objects. Returned int value has the following meanings.

1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
The following is the Student class.

public class Student
{
int rollNo;
String name;
 
public Student(int rollNo, String name)
{
this.rollNo = rollNo;
this.name = name;
}

public void setRollNo(int rollNo)
{
this.rollNo = rollNo;
}

public int getRollNo()
{
return this.rollNo;
}
public void setName(String name)
{
this.name = name;
}

public String getName()
{
return this.name;
}
 }

The following is the "students" List collection.
Stundent std1 = new Stundent(1, "Vinay");
Stundent std2 = new Stundent(2, "Kumar");
Stundent std3 = new Stundent(3,"Goyal");
Stundent std4 = new Stundent(4,"Sharma");

ArrayList students = new ArrayList();
students.add(std1);
students.add(std2);
students.add(std3);
students.add(std4);

The following is the sample code to sort an arraylist in java.

java.util.Collections.sort(students, new Comparator<Student>()
{
    public int compare(Student std1, Student std2) {
       return std1.getName().compareToIgnoreCase(std2.getName());
    }
});


Sunday, April 1, 2012

Concatenation of String array to String

This program will help to concatenate String array to a simple string with a delimiter( if require).

public class StrArrtoStr {

public static void main(String[] args) {
String weeks_days[] = new String[7];
weeks_days[0] = "Sunday";
weeks_days[1] = "Monday";
weeks_days[2] = "Tuesday";
weeks_days[3] = "Wednesday";
weeks_days[4] = "Thursday";
weeks_days[5] = "Friday";
weeks_days[6] = "Saturday";
StringBuffer finalString = new StringBuffer();

if (weeks_days.length > 0) {
finalString.append(weeks_days[0]);
for (int i = 1; i < weeks_days.length; i++) {
finalString.append(",");
finalString.append(weeks_days[i]);
}
}

System.out.println("Concatenation of String array to String:::"
+ finalString.toString());

}

}

In the above example, we have String array of length 7 having items(weeks). We need to concatenate all these into a one string.

The above program will provide a final output which is as follows:
Concatenation of String array to String::: Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday