按属性分组对象列表:Java

我需要使用特定对象的属性(位置)将对象列表(学生)分组,代码如下所示,

public class Grouping { /** * @param args the command line arguments */ public static void main(String[] args) { List<Student> studlist = new ArrayList<Student>(); studlist.add(new Student("1726", "John", "New York")); studlist.add(new Student("4321", "Max", "California")); studlist.add(new Student("2234", "Andrew", "Los Angeles")); studlist.add(new Student("5223", "Michael", "New York")); studlist.add(new Student("7765", "Sam", "California")); studlist.add(new Student("3442", "Mark", "New York")); //Code to group students by location /* Output should be Like below ID : 1726 Name : John Location : New York ID : 5223 Name : Michael Location : New York ID : 4321 Name : Max Location : California ID : 7765 Name : Sam Location : California */ for (Student student : studlist) { System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location); } } } class Student { String stud_id; String stud_name; String stud_location; Student(String sid, String sname, String slocation) { this.stud_id = sid; this.stud_name = sname; this.stud_location = slocation; } } 

请build议我一个干净的方式来做到这一点。

这将把学生对象添加到以locationID为关键字的HashMap

 HashMap<Integer, List<Location>> hashMap = new HashMap<Integer, List<Location>>(); 

迭代此代码并将学生添加到HashMap

 if (!hashMap.containsKey(locationId)) { List<Location> list = new ArrayList<Location>(); list.add(student); hashMap.put(locationId, list); } else { hashMap.get(locationId).add(student); } 

如果你想要所有的学生具有特定的位置细节,那么你可以使用这个:

 hashMap.get(locationId); 

这将让你所有的学生具有相同的位置ID。

在Java 8中:

 Map<String, List<Student>> studlistGrouped = studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location)); 
 Map<String, List<Student>> map = new HashMap<String, List<Student>>(); for (Student student : studlist) { String key = student.stud_location; if(map.containsKey(key)){ List<Student> list = map.get(key); list.add(student); }else{ List<Student> list = new ArrayList<Student>(); list.add(student); map.put(key, list); } } 

使用比较器在Java中实现SQL GROUP BY Feature,比较器将比较列数据并对其进行sorting。 基本上如果你保持sorting的数据看起来像分组数据,例如,如果你有相同的重复列数据,然后sorting机制sorting他们保持同一数据一边,然后寻找其他数据是不相似的数据。 这间接地被视为相同数据的GROUPING。

 public class GroupByFeatureInJava { public static void main(String[] args) { ProductBean p1 = new ProductBean("P1", 20, new Date()); ProductBean p2 = new ProductBean("P1", 30, new Date()); ProductBean p3 = new ProductBean("P2", 20, new Date()); ProductBean p4 = new ProductBean("P1", 20, new Date()); ProductBean p5 = new ProductBean("P3", 60, new Date()); ProductBean p6 = new ProductBean("P1", 20, new Date()); List<ProductBean> list = new ArrayList<ProductBean>(); list.add(p1); list.add(p2); list.add(p3); list.add(p4); list.add(p5); list.add(p6); for (Iterator iterator = list.iterator(); iterator.hasNext();) { ProductBean bean = (ProductBean) iterator.next(); System.out.println(bean); } System.out.println("******** AFTER GROUP BY PRODUCT_ID ******"); Collections.sort(list, new ProductBean().new CompareByProductID()); for (Iterator iterator = list.iterator(); iterator.hasNext();) { ProductBean bean = (ProductBean) iterator.next(); System.out.println(bean); } System.out.println("******** AFTER GROUP BY PRICE ******"); Collections.sort(list, new ProductBean().new CompareByProductPrice()); for (Iterator iterator = list.iterator(); iterator.hasNext();) { ProductBean bean = (ProductBean) iterator.next(); System.out.println(bean); } } } class ProductBean { String productId; int price; Date date; @Override public String toString() { return "ProductBean [" + productId + " " + price + " " + date + "]"; } ProductBean() { } ProductBean(String productId, int price, Date date) { this.productId = productId; this.price = price; this.date = date; } class CompareByProductID implements Comparator<ProductBean> { public int compare(ProductBean p1, ProductBean p2) { if (p1.productId.compareTo(p2.productId) > 0) { return 1; } if (p1.productId.compareTo(p2.productId) < 0) { return -1; } // at this point all ab,c,d are equal... so return "equal" return 0; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub return super.equals(obj); } } class CompareByProductPrice implements Comparator<ProductBean> { @Override public int compare(ProductBean p1, ProductBean p2) { // this mean the first column is tied in thee two rows if (p1.price > p2.price) { return 1; } if (p1.price < p2.price) { return -1; } return 0; } public boolean equals(Object obj) { // TODO Auto-generated method stub return super.equals(obj); } } class CompareByCreateDate implements Comparator<ProductBean> { @Override public int compare(ProductBean p1, ProductBean p2) { if (p1.date.after(p2.date)) { return 1; } if (p1.date.before(p2.date)) { return -1; } return 0; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub return super.equals(obj); } } } 

输出在这里为上面的ProductBean列表完成了GROUP BY条件,在这里如果你看到input数据给出了ProductBean到Collections.sort的列表(列表,你需要的列的Comparator对象)这将根据你的比较器实现进行sorting您将能够在下面的输出中看到GROUPED数据。 希望这可以帮助…

     ********之前分组input数据看这个方法******
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ********后面的产品_ID ******
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

     ********后群价格******
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
     ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

您可以使用以下内容:

 Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>(); for (Student student: studlist) { String key = student.stud_location; if (groupedStudents.get(key) == null) { groupedStudents.put(key, new ArrayList<Student>()); } groupedStudents.get(key).add(student); } 

//打印

 Set<String> groupedStudentsKeySet = groupedCustomer.keySet(); for (String location: groupedStudentsKeySet) { List<Student> stdnts = groupedStudents.get(location); for (Student student : stdnts) { System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location); } } 

使用Java 8

 import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; class Student { String stud_id; String stud_name; String stud_location; public String getStud_id() { return stud_id; } public String getStud_name() { return stud_name; } public String getStud_location() { return stud_location; } Student(String sid, String sname, String slocation) { this.stud_id = sid; this.stud_name = sname; this.stud_location = slocation; } } class Temp { public static void main(String args[]) { Stream<Student> studs = Stream.of(new Student("1726", "John", "New York"), new Student("4321", "Max", "California"), new Student("2234", "Max", "Los Angeles"), new Student("7765", "Sam", "California")); Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location))); System.out.println(map);//print by name and then location } } 

{Max = {Los Angeles = [Student @ 214c265e],California = [Student @ 448139f0]},John = {New York = [Student @ 7cca494b]},Sam = {California = [Student @ 7ba4f24f]}}

你可以这样sorting:

  Collections.sort(studlist, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getStud_location().compareTo(o2.getStud_location()); } }); 

假设你在学生课上还有getter的位置。

你可以这样做:

 Map<String, List<Student>> map = new HashMap<String, List<Student>>(); List<Student> studlist = new ArrayList<Student>(); studlist.add(new Student("1726", "John", "New York")); map.put("New York", studlist); 

键将是学生的位置和价值列表。 所以稍后您可以通过使用以下方式获得一组学生:

 studlist = map.get("New York"); 

你可以使用guavaMultimaps

 @Canonical class Persion { String name Integer age } List<Persion> list = [ new Persion("qianzi", 100), new Persion("qianzi", 99), new Persion("zhijia", 99) ] println Multimaps.index(list, { Persion p -> return p.name }) 

它打印:

[qianzi:[com.ctcf.message.Persion(qianzi,100),com.ctcf.message.Persion(qianzi,88)],zhijia:[com.ctcf.message.Persion(zhijia,99)]]