Two ways to group the JAVA set List

Source: Internet
Author: User

Find two ways from the Internet, the efficiency is similar, here posted code for everyone to refer to

Entity class data

public class Data {

    private Long ID;
    Private Long CourseID;
    Private String content;

    Public Long GetId () {return
        ID;
    }

    Public Data setId (Long id) {
        this.id = ID;
        return this;
    }

    Public Long Getcourseid () {return
        CourseID;
    }

    Public Data Setcourseid (Long courseid) {
        This.courseid = CourseID;
        return this;
    }

    Public String getcontent () {return
        content;
    }

    Public Data setcontent (String content) {
        this.content = content;
        return this;
    }
    

Sort class

<pre name= "code" class= "Java" >import Java.lang.reflect.Method;
Import java.util.ArrayList;
Import java.util.Collection;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.Map;

Import Com.framework.util.ParamUtils; The public class Commonutils {/** * is used to assemble the group according to * * @author Zhanglikun * @title GroupBy * @date 2013-4
	-23 */public interface groupby<t> {T GroupBy (Object obj);  }/** * * @param colls * @param GB * @return/public static final <t extends Comparable<t> d> Map<t, list<d>> Group (collection<d> Colls, groupby<t> GB) {if (Colls = null | | Colls.isempty (
			) {System.out.println ("group set cannot be empty!");
		return null;
			} if (GB = null) {SYSTEM.OUT.PRINTLN ("the group according to the interface cannot be null!");
		return null;
		} iterator<d> iter = Colls.iterator ();
		Map<t, list<d>> map = new hashmap<t, list<d>> (); while (Iter.hasnext ()) {D d =Iter.next ();
			t = gb.groupby (d);
			if (Map.containskey (t)) {Map.get (t). Add (d);
				else {list<d> List = new arraylist<d> ();
				List.add (d);
			Map.put (t, list);
	} return map; /** * List<v> in the MethodName method of V (the return value must be a K type) to be grouped into map<k, list<v>> <br> * To ensure that the methods of the incoming parameter must be V A method with a return value, and the return value must be of type K * * @param list * To be grouped @param map * To store the grouped map * @param Claz Type of Z * Generic V * @param methodname * Method name/public static <k, v> void Listgroup2map (list& Lt  V> list, map<k, list<v>> Map, class<v> clazz, String methodname) {//Entry parameter illegal row checksum if (null = List | | NULL = = Map | | Null = = Clazz | | !  Paramutils.chkstring (methodname)) {System.out.print ("Commonutils.listgroup2map join parameter error, List: + list +"; Map: "+ map +"
			Clazz: "+ Clazz +"; MethodName: "+ methodname";
		Return
		}//Get Methods method = Getmethodbyname (Clazz, MethodName); Non-null sentenceBreak if (Null = = method) {return;
	}//Formal grouping Listgroup2map (list, map, method); /** * Based on class and method names, gets the method object * * @param clazz * @param methodname * @return/public static methods Getmethodbyna
		Me (class<?> clazz, String methodname) {method method = null; The argument cannot be empty if (null = = Clazz | |! Paramutils.chkstring (methodname)) {System.out.print ("commonutils.getmethodbyname entry parameter error, Clazz: + Clazz +"; methodname
			: "+ methodname);
		return method;
		try {method = Clazz.getdeclaredmethod (methodname); The catch (Exception e) {System.out.print ("class Fetch method failed.")
		");
	return method; /** * List<v> The return value of a method of V (the return value must be a K type) to be grouped into map<k, list<v>> <br> * To ensure that the parameters of the entry must have a value of            method, and the return value must be of type K * * @param list * To be grouped @param map * To store the grouped map * @param method * Method * * @SuppressWarnings ("unchecked") public static <k, v> void Listgroup2map (list<v> List, MAP&L T K, List<v>> map, Method method) {//Entry illegal row validation if (null = List | | | null = MAP | | | null = = method) {System.out.print ("Commo
			Nutils.listgroup2map into parameter error, list: "+ list +"; Map: "+ map +"; Method: "+ method);
		Return
			try {//Start grouping Object key;
			List<v> listtmp;
				for (V val:list) {key = Method.invoke (val);
				Listtmp = Map.get (key);
					if (null = = listtmp) {listtmp = new arraylist<v> ();
				Map.put ((K) key, listtmp);
			} listtmp.add (Val); The catch (Exception e) {System.out.print group failed.
		"); }
	}

}



Test class

Import java.util.ArrayList;
Import Java.util.LinkedHashMap;
Import java.util.List;

Import Java.util.Map;

Import Com.framework.common.CommonUtils.GroupBy; public class Test {/** * @param args */public static void main (string[] args) {//Prepare a set final int loop = 1
		000 * 1000; list<data> list = new arraylist<data> (); Size=8 * loop for (int i = 0; I < loop; i++) {List.add (New Data (). SetId (1L). Setcourseid (200010L). SetContent ("A
			AA "));
			List.add (New Data (). SetId (2L). Setcourseid (200010L). SetContent ("BBB");
			List.add (New Data (). SetId (3L). Setcourseid (200011L). SetContent ("CCC");
			List.add (New Data (). SetId (4L). Setcourseid (200011L). SetContent ("DDD");
			List.add (New Data (). SetId (5L). Setcourseid (200010L). SetContent ("EEE"));
			List.add (New Data (). SetId (6L). Setcourseid (200011L). SetContent ("FFF"));
			List.add (New Data (). SetId (7L). Setcourseid (200010L). SetContent ("GGG"));
		List.add (New Data (). SetId (8L). Setcourseid (200012L). SetContent ("HHH")); }
		// To group 1 long time = System.currenttimemillis ();
		Map<long, list<data>> map2 = new Linkedhashmap<long, list<data>> (); Commonutils.listgroup2map (list, map2, Data.class, "getId")//Input Method name Long Duration = System.currenttimemillis ()-Time

		;

		SYSTEM.OUT.PRINTLN ("Group One Execution:" + duration + "Millisecond!");
		Group Two time = System.currenttimemillis (); Map<long, list<data>> map = Commonutils.group (List, New groupby<long> () {@Override public Long gr
				Oupby (Object obj) {Data d = (data) obj; return D.getcourseid ();

		GROUP BY Course ID}});

		Duration = System.currenttimemillis ()-time;

	SYSTEM.OUT.PRINTLN ("Group II Execution:" + duration + "milliseconds!");
 }

}


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.