Group list of objects by attribute: Java

I need to group a list of objects (Student) using the attribute (Location) of a particular object, the code looks like below,

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; } } 

Please suggest me a clean way to do this.

+81
java list grouping
Feb 10 '14 at 13:21
source share
11 answers

This will add the student object to the HashMap with the locationID key.

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

Follow this code and add students to the HashMap :

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

If you want all students with specific location data, you can use this:

 hashMap.get(locationId); 

which will provide you all students with the same location id.

+109
Feb 10 '14 at
source share

In Java 8:

 Map<String, List<Student>> studlistGrouped = studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location)); 
+209
May 12 '15 at
source share
 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); } } 
+28
Feb 10 '14 at 13:35
source share

Using 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 } } 

The result will be:

 { Max={ Los Angeles=[Student@214c265e], California=[Student@448139f0] }, John={ New York=[Student@7cca494b] }, Sam={ California=[Student@7ba4f24f] } } 
+8
Apr 15 '16 at 6:31
source share

You can use the following:

 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); } 

// print

 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); } } 
+4
Feb 10 '14 at
source share

To implement the SQL GROUP BY function in Java using Comparator, the comparator will compare your column data and sort them. Basically, if you save sorted data that looks like grouped data, for example, if you have the same duplicate column data, then sort the mechanism by sorting them, keeping the same data on the one hand, and then look for other data that are heterogeneous data. This is indirectly viewed as GROUPING from the same data.

 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); } } } 

The output here for the ProductBean list above is executed with GROUP BY criteria, here, if you see the input data that is listed in the ProductBean list for Collections.sort (list, Comparator object for the desired column). It will be sorted based on your comparator implementation, and you can see the GROUPED data in the lower format. Hope this helps ...

     ******** BEFORE GROUPING INPUT DATA LOOKS THIS WAY ******
     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]
     ******** AFTER GROUP BY PRODUCT_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]

     ******** AFTER GROUP BY PRICE ******
     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]

+4
Nov 17 '14 at 4:14
source share

You can do the following:

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

Assuming you also have a recipient to place in your Student class.

+1
Feb 10 '14 at
source share

You can do it:

 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); 

The keys will be locations and a list of student values. So later, you can get a group of students by simply using:

 studlist = map.get("New York"); 
0
Feb 10 '14 at 13:30
source share

you can use guava Multimaps

 @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 }) 

he prints:

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

0
Sep 26 '17 at 7:46 on
source share
 Function<Student, List<Object>> compositKey = std -> Arrays.asList(std.stud_location()); studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList())); 

If you want to add multiple objects for a group, you can simply add the object in the compositKey method, separating it with a comma:

 Function<Student, List<Object>> compositKey = std -> Arrays.asList(std.stud_location(),std.stud_name()); studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList())); 
0
Feb 12 '18 at 11:37
source share
 public class Test9 { static class Student { String stud_id; String stud_name; String stud_location; public Student(String stud_id, String stud_name, String stud_location) { super(); this.stud_id = stud_id; this.stud_name = stud_name; this.stud_location = stud_location; } public String getStud_id() { return stud_id; } public void setStud_id(String stud_id) { this.stud_id = stud_id; } public String getStud_name() { return stud_name; } public void setStud_name(String stud_name) { this.stud_name = stud_name; } public String getStud_location() { return stud_location; } public void setStud_location(String stud_location) { this.stud_location = stud_location; } @Override public String toString() { return " [stud_id=" + stud_id + ", stud_name=" + stud_name + "]"; } } public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); list.add(new Student("1726", "John Easton", "Lancaster")); list.add(new Student("4321", "Max Carrados", "London")); list.add(new Student("2234", "Andrew Lewis", "Lancaster")); list.add(new Student("5223", "Michael Benson", "Leeds")); list.add(new Student("5225", "Sanath Jayasuriya", "Leeds")); list.add(new Student("7765", "Samuael Vatican", "California")); list.add(new Student("3442", "Mark Farley", "Ladykirk")); list.add(new Student("3443", "Alex Stuart", "Ladykirk")); list.add(new Student("4321", "Michael Stuart", "California")); Map<String, List<Student>> map1 = list .stream() .sorted(Comparator.comparing(Student::getStud_id) .thenComparing(Student::getStud_name) .thenComparing(Student::getStud_location) ) .collect(Collectors.groupingBy( ch -> ch.stud_location )); System.out.println(map1); /* Output : {Ladykirk=[ [stud_id=3442, stud_name=Mark Farley], [stud_id=3443, stud_name=Alex Stuart]], Leeds=[ [stud_id=5223, stud_name=Michael Benson], [stud_id=5225, stud_name=Sanath Jayasuriya]], London=[ [stud_id=4321, stud_name=Max Carrados]], Lancaster=[ [stud_id=1726, stud_name=John Easton], [stud_id=2234, stud_name=Andrew Lewis]], California=[ [stud_id=4321, stud_name=Michael Stuart], [stud_id=7765, stud_name=Samuael Vatican]]} */ }// main } 
0
Aug 18 '19 at 12:52
source share



All Articles