Java algorithm practices classify elements in a list by attributes into a tree-like map__java--other

Source: Internet
Author: User
Tags dateformat tojson
Java algorithm practice, but also a useful tool class.
For example: A student Information list, the student's information by class, gender, school number, etc., will list according to class, gender classification.
Just:
Map map = Collectiontools.classifylist (studentalllist,
"ClassId", "sex");

This tool uses reflection to classify each student in the list into a tree map according to ClassID and sex.

Package utils;
Import java.lang.reflect.InvocationTargetException;
Import java.util.ArrayList;
Import Java.util.LinkedHashMap;
Import java.util.List;
 
Import Java.util.Map;
Import Org.apache.commons.beanutils.PropertyUtils; /** * * @author Klguang * @version 0.1/public class Collectiontools {/** * use Propertyutils to get the value of the bean, and root
     According to KeyName classified * @param list * List beans * @param keyname * Name of the bean that needs to be categorized * @return linkedhashmap<string, List&gt, map<br> in order the key of the map is the property name + "#" of the bean that needs to be sorted and the corresponding attribute value: Eg: "CLA ss#312 "<br> * value is list<bean><br> * * @throws illegalaccessexception * @th Rows InvocationTargetException * @throws nosuchmethodexception * * public static linkedhashmap<string, L Ist> Classify (list list, String KeyName) throws Illegalaccessexception, InvocationTargetException, Nosuchme thodexception {linkedhashmap<String, list> target = new Linkedhashmap (); For (object obj:list) {//Get the value of the property (KeyName) that the bean needs to categorize, do not type convert Object Okeyvalue = PROPERTYUTILS.GETP
            Roperty (obj, keyname);
            String keyvalue = KeyName + "#" + string.valueof (okeyvalue);  if (!target.containskey (keyvalue)) {//If there is no collation key value in the map, add the key value and the corresponding list ArrayList keylist =
                New ArrayList ();
                Keylist.add (obj);
            Target.put (KeyValue, keylist); else {//If there is a collation key value, add the bean ArrayList keylist = (ArrayList) target.get in the appropriate list (Keyval
                UE);
            Keylist.add (obj);
    } return target; /** * * Will classify the map<string, list> according to KeyName classification, and the index control recursion.
     <br> * Because the direct call is meaningless, this method is private, * * @param MOCL * Map of Classified list<br> * The Application Method <br> * linkedhashmap<
     String, list> classify (list list, String * keyname) <br> * classify List as map<br>            * * @param index * with conditions index < Keynames.length control recursion * * @param keynames *
     The property name of the bean that needs to be categorized * @return * @throws illegalaccessexception * @throws invocationtargetexception * @throws nosuchmethodexception * * private static linkedhashmap<string, map> classify (map<string, List
            > mocl, int index, String ... keynames) throws Illegalaccessexception, InvocationTargetException,
        nosuchmethodexception {//Single Step Understanding: Target is a function parameter map<string, list> Mocl again categorized as linkedhashmap<string,map>
        Recursion to the end this is the final categorized Map linkedhashmap<string, map> target = new Linkedhashmap ();
        Control the recursive condition, the starting index should always be 1. if (Index < keynames.length) {//swap is used to hold the value of the parameter index, this is one of the most error-prone places//guarantees: In the parameter map<string, List > MoThe CL layer loops with the same index parameter value.
            int swap = index;
                For (map.entry<string, list> entry:mocl.entrySet ()) {String Mocl_key = Entry.getkey ();
                List mocl_list = Entry.getvalue ();
                The list<bean> is reclassified again linkedhashmap<string, list> _MOCL = classify (mocl_list, Keynames[index]);
                    If index reaches the last of the array, it must be list<bean> to map, recursive End if (index = = keynames.length-1) {
                Target.put (Mocl_key, _MOCL);
                    else {//_MOCL list<bean> to map, reclassified//_MOCM as the abbreviation for map of classified map
                    linkedhashmap<string, map> _mocm = classify (_MOCL, ++index, keynames);
                Target.put (Mocl_key, _MOCM);
            index = swap;
    } return target; /** * will map<string, list> map is categorized according to the property name KeyName The bean needs to categorize * @Map * @param keyname * param map * Map of Classified list<br> * List  The property name of the bean that needs to be categorized * @return * @throws illegalaccessexception * @throws invocationtargetexception * @throws nosuchmethodexception * * public static linkedhashmap<string, map> Classifymap (map<string, Lis
        t> map, String KeyName) throws Illegalaccessexception, InvocationTargetException, nosuchmethodexception {
        linkedhashmap<string, map> target = new Linkedhashmap ();
            For (map.entry<string, list> entry:map.entrySet ()) {List map_list = Entry.getvalue ();
            String Map_key = Entry.getkey ();
            linkedhashmap<string, list> keymap = classify (map_list, keyname);
        Target.put (Map_key, keymap);
    return target; /** * Classifies list<bean> according to the properties of the specified bean, and the keynames order affects the collation results. <br> * Eg: A student list, categorized according to class and sex &LT;BR&GT            * Map map = collectionutils.classifylist (studentlist, "classId", "Sex");<br> * * @param list *         List Beans * @param keynames * Array contains the name of the property of the bean that needs to be categorized * @return sorted tree map<br> * The key of the map is the property name + "#" + corresponding property value for the bean that needs to be categorized: eg: "class#312" <br> * Map has a value of list or map * * @th Rows illegalaccessexception * @throws invocationtargetexception * @throws nosuchmethodexception * * Publ IC Static Linkedhashmap classifylist (List list, String ... keynames) throws Illegalaccessexception, Invocationt
        Argetexception, Nosuchmethodexception {if (keynames = null | | | keynames.length = = 0) return null;
        if (keynames.length = = 1) return classify (list, keynames[0]);
    else return classify (classify (list, keynames[0]), 1, keynames); }
}


Package test;
Import java.lang.reflect.InvocationTargetException;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;
 
Import Java.util.Map; Import Utils.
Collectiontools; Import Utils.
 
Jsonutil; public class Collectionclassifytest {/** * @param args * @throws nosuchmethodexception * @throws INV Ocationtargetexception * @throws illegalaccessexception */public static void main (string[] args) throws Ill Egalaccessexception, InvocationTargetException, nosuchmethodexception {//TODO auto-generated method Stub list<student> studentalllist = new ArrayList ()//So Class of students Studentalllist.add (new Student ("1
        "," A ", 1," Ⅰ "," North "," 1 "));
        Studentalllist.add (New Student ("2", "C", 1, "Ⅱ", "Upper", "0"));
        Studentalllist.add (New Student ("3", "C", 1, "Ⅰ", "North", "1"));
        Studentalllist.add (New Student ("4", "B", 1, "Ⅰ", "Wide", "1")); Studentalllist.add(New Student ("5", "A", 1, "Ⅳ", "Guang", "1"));
        Studentalllist.add (New Student ("6", "C", 1, "Ⅳ", "Upper", "0"));
        Studentalllist.add (New Student ("7", "A", 1, "Ⅳ", "Wide", "0"));
        Studentalllist.add (New Student ("8", "B", 1, "Ⅰ", "Wide", "0"));
        Studentalllist.add (New Student ("8", "D", 1, "Ⅲ", "North", "0"));
        Studentalllist.add (New Student ("8", "D", 1, "Ⅲ", "Wide", "0"));
 
         Studentalllist.add (New Student ("8", "D", 1, "Ⅲ", "Upper", "0"));
          
          
         Map map = collectiontools.classifylist (studentalllist, "classId", "sex");
         SYSTEM.OUT.PRINTLN (Jsonutil.tojson (map));
         
        Do contrast//system.out.println (Jsonutil.tojson (Classifytest (studentalllist)));
        Date Begin=new date (); for (int i = 0; i < 1000000 i++) {//Map map = Collectionutils.classifylist (studentalllist, "province", "a
Cademyid ",//" ClassId "," Team "," sex "); SYSTEM.OUT.PRINTLN (Jsonutil.tojson (map));
        }//date end=new Date ();
         
 
    System.out.println (End.gettime ()-begin.gettime ());  } static Map Classifytest (list<student> studentalllist) {//step 1 map<string, list> map =
        New hashmap<string, list> ();
        map<string, object> maplast = new hashmap<string, object> (); for (Student student:studentalllist) {for (Iterator it = Studentalllist.iterator (); It.hasnext ();)
 
            {Student Student = (Student) it.next (); if (Map.containskey (STUDENT.GETCLASSID)) {//If the array already exists, put it here List studentlist = Map.get (student.getcla
                SsId ());
            Studentlist.add (student);
                else {List studentlist = new ArrayList ();////re-declare an array List studentlist.add (student);
            Map.put (Student.getclassid (), studentlist);
 
        }//System.out.println (Jsonutil.tojson (map)); //Step 2//Use data grouped by processing 1 steps, GROUP by gender/female again for (map.entry<string, list> m:map.entryset ()) {//Key value traversal Map Map maplist = new HashMap (); List Studentsingle = M.getvalue (); Students of the same class, men and women List studentlistmen = new ArrayList (); Declare a store boy's list List studentlistwomen = new ArrayList (); Declare a girl's list for (iterator it = Studentsingle.iterator (); It.hasnext ();)
                {//traverse Student Student = (Student) it.next ();
                    if ("0". Equals (Student.getsex ())) {//male studentlistmen.add (student);//boy} else { Studentlistwomen.add (student);
            Girls} maplist.put ("female", studentlistwomen);
            Maplist.put ("Male", studentlistmen);
        Maplast.put (M.getkey (), maplist);
    return maplast; }
}


Package test;  /** * @author Klguang * */public class Student {private string StudentID;//School number private string sex;//Sex 0 men
    1 female private int team;
    Private String classId;
     
    private string academyid;//College private string Province;
        Public Student (String StudentID, String classId, String sex) {super ();
        This.studentid = StudentID;
        This.classid = classId;
    This.sex = sex;
        Student (String StudentID, String Classid,int team, string sex) {super ();
        This.studentid = StudentID;
        This.classid = classId;
        This.team=team;
    This.sex = sex;
        Student (String StudentID, String Classid,int team, string academyid,string sex) {super ();
        This.studentid = StudentID;
        This.classid = classId;
        This.team=team;
        This.sex = sex;
    This.academyid=academyid; Student (String StudentID, String Classid,int team, String Academyid,string province,string Sex) {super ();
        This.studentid = StudentID;
        This.classid = classId;
        This.team=team;
        This.sex = sex;
        This.academyid=academyid;
    This.province=province;
    Public String GetClassID () {return classId;
    } public void Setclassid (String classId) {this.classid = ClassId;
    Public String Getstudentid () {return studentid;
    } public void Setstudentid (String studentid) {this.studentid = StudentID;
    Public String Getsex () {return sex;
    } public void Setsex (String sex) {this.sex = sex;
    public int Getteam () {return team;
    public void Setteam (int team) {this.team = team;
    Public String Getacademyid () {return academyid;
    } public void Setacademyid (String academyid) {This.academyid = Academyid; Public String getprovince () {REturn Province;
    } public void Setprovince (String province) {this.province = province; }   
}


Package utils;
 
Import Java.util.Date;
Import Com.alibaba.fastjson.JSON;
Import Com.alibaba.fastjson.serializer.SerializeConfig;
Import Com.alibaba.fastjson.serializer.SerializerFeature;
 
Import Com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
    public class Jsonutil {private static serializeconfig mapping = new Serializeconfig ();
    private static String DateFormat;
    static {DateFormat = "yyyy-mm-dd HH:mm:ss"; public static String Tojson (Object jsontext) {return json.tojsonstring (Jsontext, serializer
    Feature.writedateusedateformat); public static string Tojson (string dateformat, Object jsontext) {mapping.put (Date.class, New Simpledatefo
        Rmatserializer (DateFormat));
    Return json.tojsonstring (jsontext, mapping); public static String Torealjson (Object jsontext) {return json.tojsonstring (jsontext,serializerfeature.
    Disablecircularreferencedetect); }
}


{"classid#a": {"sex#1": [{"Academyid": "Ⅰ", "classId": "A",
            "Province": "North", "Sex": "1", "StudentID": "1", "Team": 1 }, {"Academyid": "Ⅳ", "classId": "A", "province": "Wide
        "," Sex ":" 1 "," StudentID ":" 5 "," Team ": 1}], "Sex#0": [{"Academyid": "Ⅳ", "classId": "A", "Province": " 
    Wide "," Sex ":" 0 "," StudentID ":" 7 "," Team ": 1}]},
                "Classid#c": {"sex#0": [{"Academyid": "Ⅱ", "classId": "C",
            "Province": "On", "Sex": "0", "StudentID": "2", "Team": 1 },
            {
                "Academyid": "Ⅳ", "classId": "C", "Province": "Up", "sex":
            "0", "StudentID": "6", "Team": 1}], "sex#1": [ {"Academyid": "Ⅰ", "classId": "C", "Province": "North", "sex"
        : "1", "StudentID": "3", "Team": 1}]}, "classid#b": { "Sex#1": [{"Academyid": "Ⅰ", "classId": "B", "Province":
        "Guang", "Sex": "1", "StudentID": "4", "Team": 1}],  "Sex#0": [{"Academyid": "Ⅰ", "classId": "B", "Province":
    "Guang", "Sex": "0", "StudentID": "8", "Team": 1}]
  }, "classid#d": {      "Sex#0": [{"Academyid": "Ⅲ", "classId": "D", "Province
            ":" North "," Sex ":" 0 "," StudentID ":" 8 "," Team ": 1}, {"Academyid": "Ⅲ", "classId": "D", "province": "Wide", "sex ":" 0 "," StudentID ":" 8 "," Team ": 1}, {" Academyi D ":" Ⅲ "," ClassId ":" D "," Province ":" Up "," Sex ":" 0 "," Stu Dentid ":" 8 "," Team ": 1}]}}




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.