Thursday, January 29, 2009

Meagan Good Haircut 2010

Order Lists in Java

Well, sort a list in Java, is very simple, all we have to do is call the Sort method of Collections class, how to send parameter we want to sort the list and the order given the natural order of the object (Comparable interface), and if you do not want that, then we can create a Comparator. However, imagine that we have about 20 different objects, which are JavaBeans, and we need to sort many times with different properties such as Name, Last Name, Mother's Maiden Name or Address. We should be creating Comparators for each of the properties that have the JavaBean and so then we can sort. Would at least more than 20 different implements almost Comparators the same logic, comparing a bean for some of its properties, complicated no?. Well a solution for this is the Java Reflection API





Well To boot it is necessary to create the signature of our method, which can be made to a utility class that has methods that we use for our application, then the signature member of our method is as follows:

 
import java.util.List;


public class Util {public static void

orders (List list, String property) {

}}



only thing will make the method will receive a list which computers, and property by which we order it. That is going to sort a list of people by age, then all you have to do is call our method commands (list, "name"), where list is the List of People and name is a JavaBeans property is setNombre say methods () and getName ().



Well, now you move on to the fun part, to do this, all you have to do is send calling the sort method of Collections class (the original idea) and create a Comparator. Only the Comparator, called the properties of objects at runtime using the Java Reflection API. So far we have is this:

 

import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class Util {public static void

orders (List list, String property) {
Collections.sort (list, new Comparator () {public int
compare (Object arg0, Object arg1) {
return 0;

}});
}}








Now what we have to do is call getPropiedad methods of each of the objects and compare them. This is accomplished by calling the getClass () of class Object, then with that Class llamamaos al método getMethod() y se le manda como pararametro el nombre del método el cual sera getXXXXX donde XXXXX es nuestra propiedad, por ejemplo "nombre" llamara al método getNombre. Y finalmente se invocan esos métodos para obtener las propiedades y luego compararlas. El método invoke() de la clase Method, regresa siempre Object y si el método regresa tipos primitivos regresa su clase encapsuladora (int->Integer etc...).

  
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class Util {

public static void ordena(List lista, final String propiedad) {
Collections.sort (list, new Comparator () {public int

compare (Object obj1, Object obj2) {Class class =

obj1.getClass ();
String getter = "get" + Character.toUpperCase (property . charAt (0)) + propiedad.substring (1);

try {Method getPropiedad = clase.getMethod (getter);
feature1 = getPropiedad.invoke
Object (obj1);
getPropiedad.invoke Object property2 = (obj2) ;

/ / STILL have to compare


} catch (Exception e) {
e.printStackTrace ();}






return 0;

}});

}}





Finally we just need to compare properties for this use the instanceof operator to see if the property is comparable using compareTo ( ), otherwise we will use the method equals to compare objects are equal if not return 1 (which actually it is not very useful anyway haha, but it's the only thing you can do.) In addition to the parameter of the property, we have to add the final choice because it will be used within the Comparator class that we are defining internally.

 

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;



public class useful

{public static void sort (List list final String property) {
Collections.sort (list, new Comparator () {public int

compare (Object obj1, Object obj2) {Class class =

obj1.getClass ();
String getter = "get" + Character.toUpperCase (propiedad.charAt (0)) + propiedad.substring (1);

try {Method = getPropiedad clase.getMethod (getter);

Object propiedad1 getPropiedad.invoke = (obj1);
Object property2 = getPropiedad.invoke (obj2);

if (feature1 feature2 instanceof Comparable & & instanceof Comparable) {Comparable
prop1 = (Comparable) feature1;
Comparable Prop2 = (Comparable) property2;
prop1.compareTo return (Prop2) ;
} / / IF NOT COMPARABLE

else {if (propiedad1.equals (property2))
return 0;

else return 1;}




} catch (Exception e) {e.
printStackTrace ();

} return 0;

}});}



}



Well this way we have finished our method, now we just need to try it, and for this we will create a Main, a list of objects of class Person, which is a JavaBean and order. Also add an annotation method to delete the Warnings and the compiler is not giving can haha. Finally our class looks like:

 
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util. List;



public class Util {

@ SuppressWarnings ("unchecked") Public static void
orders (List list, final String property) {
Collections.sort (list, new Comparator () {public int

compare (Object obj1, Object obj2) {Class class =

obj1.getClass ();
String getter = "get" + Character.toUpperCase (propiedad.charAt (0)) + propiedad.substring (1);

try {Method getPropiedad = clase.getMethod (getter);
Object
getPropiedad.invoke feature1 = ( obj1);
getPropiedad.invoke Object property2 = (obj2);

if (feature1 feature2 instanceof Comparable & & instanceof Comparable) {Comparable
prop1 = (Comparable) feature1;
Comparable Prop2 = (Comparable) property2;
prop1.compareTo return (Prop2)
} / / IF NOT COMPARABLE

else {if (propiedad1.equals (property2)) return
0;

else return 1;}




} catch (Exception e) {
e.printStackTrace ();

} return 0;

}});


} public static void main (String [] args) {List
\u0026lt;person> \u0026lt;person> people = new ArrayList ();


personas.add (new Person ("Gustavo", 25));
personas.add (new Person ("Peter", 32));
personas.add (new Person ("Paul", 15));
people. add (new Person ("John", 10));
personas.add (new Person ("Ramiro", 50));
personas.add (new Person ("Daniel", 81));
personas.add ( new Person ("Hector", 23));

System.out.print ("Unordered List");
System.out.println (people);
System.out.println ();


/ / CALL TO ORDER BY NAME
orders (people, "name");
System.out.print ("Sorted by name:");
System.out.println (people)
System.out.println ();

/ / CALL TO ORDER BY AGE
orders (people, "age");
System.out.print ("Sorted by age");
System.out.println ( people);
System.out.println ();}






} class Person {String name

;
int age;



public Person (String name, int age) {super
( )
this.name = name;
this.edad = age;

} public String getName () {return name
;
} public void
setNombre (String name) {this.name = name
; } Public int

getEdad () {return
age
} public void
SETEDER (int age) {
this.edad = age;}


/ / JUST BE EASIER TO SEE THE DATA
public String toString () {return
name + "" + age;
}}







still have some things to add to our method, how to correct handling of exceptions, put it in a more appropriate class etc. .. But Essence is finished and we can use and reuse many of our projects!



I hope you have served
Greetings


0 comments:

Post a Comment