3:53 pm - Tuesday March 25, 9788

The Collection Program sort the specified list

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

 

The sort(List<T>, Comparator<? super T>) method is used to sort the specified list according to the order induced by the specified comparator.

Example Program


import java.util.*;

public class Comparator1 {
static public myStudent[] A = new myStudent[10];
static myStudent myStd;
static Integer myKey;

public static void main(String args[]) throws Exception {
int i;
ArrayList tab1 = new ArrayList();
System.out.println("<---Sort in Alphabetical order-->");
getData(A);
// insert elements into arraylist
for (i = 0; i < 10; i++)
tab1.add(A[i]);
// now sorting
Collections.sort(tab1, new Comparator() {
public int compare(myStudent A, myStudent B) {
return A.name.compareTo(B.name);
}
});
// listing all elements after sorting
for (i = 0; i < tab1.size(); i++)
System.out.println(tab1.get(i));
}

static void getData(myStudent[] x) {
x[0] = new myStudent(100, "Anand");
x[1] = new myStudent(101, "Siva");
x[2] = new myStudent(102, "Mani");
x[3] = new myStudent(103, "Subbu");
x[4] = new myStudent(104, "kumar");
x[5] = new myStudent(105, "Vishnu");
x[6] = new myStudent(106, "Ravi");
x[7] = new myStudent(107, "Mathu");
x[8] = new myStudent(108, "Gowtham");
x[9] = new myStudent(109, "Kesavan");
}
}

class myStudent {
public Integer BPnumber;
public String name;

myStudent(int n, String s) {
BPnumber = new Integer(n);
name = s;
}

public String toString() {
return (BPnumber + "--" + name);
}
}

Output:

<—Sort in Alphabetical order–>

100–Anand

108–Gowtham

109–Kesavan

104–Kumar

102–Mani

107–Mathu

106–Ravi

101–Siva

103–Subbu

105—Vishnu


Explanation:

sort(List<T> list, Comparator<? super T> c)

The sort(List<T>, Comparator<? super T>) method is used to sort the specified list according to the order induced by the specified comparator.

Parameters:

list – the list to be sorted.

c – the comparator to determine the order of the list. A null value indicates that the elements’ natural ordering should be used.

Throws:

ClassCastException – if the list contains elements that are not mutually comparable using the specified comparator.

UnsupportedOperationException – if the specified list’s list-iterator does not support the set operation.

IllegalArgumentException – (optional) if the comparator is found to violate the Comparator contract

 

 

BACK

 

Filed in: Z-A All Java Codes

Comments are closed.