Hi
All we ever bumped to order items from a list of java (java.util.List) I know many will say that it could do with the database adding an order by campo_de_tbl, but many applications do not require it and to do this deal java.util.Comparator.
Step 1. Create a bean, for practical purposes all the attributes are String: public class Concept
{private String id;
cve private String;
private String description;
private String value;
getValor
public String getId () {return id } public void setId (String id) {this.id = id
;}
getCve public String () {return
cve;
} public void
setCve (String cve) {
this.cve = cve;
} public String getDescription () {
return description;}
public void
setDescripcion (String description) {
this.descripcion = description;}
} Suppose we want to sort our data from our List Through The cve attribute.
Step 2. Create the class that implements the interface ConceptoComparator
Comparator
import java.util.Comparator;
ConceptoComparator public class implements Comparator {public int
compare (Object arg0, Object arg1) {
Concept withA = (Concept) arg0;
Concept with b = (Concept) arg1;
Long cveConA = Long.parseLong (conA. getCve ());
Long cveConB = Long.parseLong (conB.getCve ());
if (cveConA
return -1;
else if (cveConA> cveConB)
return 1;
return 0;
/ / TODO Auto-generated method stub}
} java.util.Comparator int compare (T a, T b) compares two objects and gives a negative value if a comes before b, zero if they are considered identical in ranking order, and a positive value if a comes after b .
Step 3: call (...) method
List Collections.sort
concepts = new ArrayList ();
Concept
con1 = new Concept (); < cveConB)
con1.setCve ("10017");
CON2 concept = new Concept ();
con2.setCve ("20001");
Concept
con3 = new Concept ();
con3.setCve ("10001");
conceptos.add (con1);
conceptos.add (CON2);
conceptos.add (Con 3);
System.out.println ("unsorted");
for (Concept with: concepts) {
System.out.println ("" + with . getCve ());}
Collections.sort (concepts, new ConceptoComparator ());
("" + con.getCve ());}
the result will be something like this:
unordered
20001 10017 10001
sorted
10001 10017
20001
0 comments:
Post a Comment