JAVA object arrays are sorted by multiple attributes __java

Source: Internet
Author: User
Tags collator reflection

The following can be directly used to run, you can also download the attachment package directly, the compiler can see the effect of running directly.

//objectsort

Package sort;

Import java.util.ArrayList;
Import java.util.Collections;
Import java.util.List;

public class Objectsort {
/**
* @param args
*/
public static void Main (string[] args) {
/**
*

* Purpose: Sort by one or some of the attributes of an object
* Java contains 8 basic data types, respectively: Boolean, Byte, char, short, int, float, douboe, long
* Compare Non-Boolean and byte-type attributes, and most use environment adaptation, if there are special requirements, please modify them yourself.
* When used, simply pass the object's property list and the ordered list to
* **/
List Arraydemo = new ArrayList ();

person P1 = new person ();
P1.setname ("Zhang San");
P1.setage (22);
P1.setsalary (160);

person P2 = new person ();
P2.setname ("Zhang San");
P2.setage (22);
P2.setsalary (150);

Person P3 = new person ();
P3.setname ("Zhang San");
P3.setage (25);
P3.setsalary (1900);

person P4 = new person ();
P4.setname ("Zhao Liu");
P4.setage (25);
P4.setsalary (3000);

Person P5 = new person ();
P5.setname ("Liu Qi");
P5.setage (30);
P5.setsalary (2000);

Arraydemo.add (p1);
Arraydemo.add (p2);
Arraydemo.add (p3);
Arraydemo.add (p4);
Arraydemo.add (p5);

Start comparing ********//
Commoncomparator comparator = new Commoncomparator ();
System.out.println ("1.sort by name, age and Salary");
Comparator.setfields_user (New string[]{"name", "Age", "salary"});
Collections.sort (Arraydemo, comparator);
for (int i=0;i<arraydemo.size (); i++)
{
person who = (person) arraydemo.get (i);
System.out.println ("Name:" +person.getname () + "Age:" +person.getage () + "Salary:" +person.getsalary ());
}

System.out.println ("1.sort by name, age");
Comparator.setfields_user (New string[]{"name", "Age"});
Collections.sort (Arraydemo, comparator);
for (int i=0;i<arraydemo.size (); i++)
{
person who = (person) arraydemo.get (i);
System.out.println ("Name:" +person.getname () + "Age:" +person.getage () + "Salary:" +person.getsalary ());
}
}

}

//commoncomparator

Package sort;

Import Java.lang.reflect.Method;
Import Java.math.BigDecimal;
Import Java.text.CollationKey;
Import Java.text.Collator;
Import Java.util.Comparator;

public class Commoncomparator implements Comparator {

/***
* @param
* The properties of the comparison object are passed in the form of string[]
* The object of comparison must conform to JavaBean, that is to have Set,get method
* */
string[] Fields_user = null;


Public string[] Getfields_user () {
return fields_user;
}
public void Setfields_user (string[] fields_user) {
This.fields_user = Fields_user;
}
/**
* Define Collation
* If you are sorting by more than one attribute
* This is sorted according to the order of the attributes, which are SQL orders by
* That is, just compare the properties of the same position to stop
* */
public int Compare (object Obj1, Object obj2)
{
No attributes, no sorting
if (Fields_user = null | | fields_user.length<=0)
{
return 2;//not compare
}
for (int i=0;i<fields_user.length;i++)
{
Return Comparefield (Obj1,obj2,fields_user[i]);
if (Comparefield (Obj1,obj2,fields_user[i]) >0)
{//If Obj1 property value is greater than Obj2 property value, returns a positive number
return 1;
}else if (Comparefield (obj1,obj2,fields_user[i)) <0) {
return-1;
}
}
return 0;
}
/**
* @param fieldName
* Sorted by attribute name
* */
private static int Comparefield (Object o1,object o2,string fieldName)
{
Try
{
Object value1 = Getfieldvaluebyname (FIELDNAME,O1);
Object value2 = Getfieldvaluebyname (FIELDNAME,O2);

--string comparison
if (value1 instanceof String)
{
String v1 = getfieldvaluebyname (fieldname,o1). toString ();
String v2 = getfieldvaluebyname (FIELDNAME,O2). toString ();
Collator mycollator = Collator.getinstance ();
Collationkey[] keys = new COLLATIONKEY[5];
Keys[0] = Mycollator.getcollationkey (v1);
KEYS[1] = Mycollator.getcollationkey (v2);
Return (Keys[0].compareto (keys[1]));
}
--Non-comparison properties not compared
else if ("Java.lang.Boolean". Equals (Value1.getclass (). GetName ()) | | "Java.lang.Byte". Equals (Value1.getclass (). GetName ()))
{
return 0;
}else
{
BigDecimal B1 = new BigDecimal (value1.tostring ());
BigDecimal b2 = new BigDecimal (value2.tostring ());
Return B1.compareto (B2);
}

catch (Exception e)
{
System.out.println ("-----------------------------------------------------------------------------");
System.out.println ("---------object does not exist or does not allow reflection of this property at this security level, please refer to Java DOC--------");
System.out.println ("-----------------------------------------------------------------------------");
E.printstacktrace ();
}
Less than
return-1;
}
/**
* @param
* FieldName Property name
* Obj Object
* Reflection Gets the value of this property
* */
private static Object Getfieldvaluebyname (String fieldname,object obj)
{
Try
{
String letter = fieldname.substring (0,1). toUpperCase ();
String methodstr = "Get" +letter+fieldname.substring (1);
Method method = Obj.getclass (). GetMethod (Methodstr, New class[]{});

Object value = Method.invoke (obj, new object[]{});

return value;
}catch (Exception e)
{
System.out.println ("------------------------------------------------------");
System.out.println ("---------the" +fieldname+ "property does not exist----------------------");
System.out.println ("------------------------------------------------------");
return null;
}
}


}

//person

Package sort;

public class Person {
Public person () {}

private String name;
private int age;
Private long salary;

Public long getsalary () {
return salary;
}
public void Setsalary (long salary) {
This.salary = salary;
}
public int getage () {
return age;
}
public void Setage (int age) {
This.age = age;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}

}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.