Group a list of objects by an attribute : Java

java list group by multiple fields
java 7 collection group by
java group list of objects by date
java 8 group by multiple fields and sum
java 8 groupingby(map values)
java 8 group by multiple fields and count
list to map of list java 8
group by in java 7

I need to group a list of objects(Student) using an attribute(Location) of the particular object, the code is 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 it.

This will add the students object to the HashMap with locationID as key.

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

Iterate over this code and add students to the HashMap:

if (!hashMap.containsKey(locationId)) {
    List<Student> list = new ArrayList<Student>();
    list.add(student);

    hashMap.put(locationId, list);
} else {
    hashMap.get(locationId).add(student);
}

If you want all the student with particular location details then you can use this:

hashMap.get(locationId);

which will get you all the students with the same the location ID.

How to do GROUP BY in Java 8? Collectors , In this Java 8 tutorial, you will learn how to group by a list of objects based on their properties. For those, who think Java 8 is just about lambda� How to group a list of objects by one of the object’s attribute, which is similar to SQL group by statement and having the same results. Object example @Data class Truck { private Integer id ; private String plateNumber ; private String truckType ; // 5t, 8t, 11t, and etc. private Integer loadCapacity ; } List < Truck > trucks = findAll

In Java 8:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

Java group list objects by attribute, How to group a list of objects by one of the object's attribute, which is similar to SQL group by statement and having the same results. In this article, we will show you how to use Java 8 Stream Collectors to group by, count, sum and sort a List.. 1. Group By, Count and Sort. 1.1 Group by a List and display the total count of it.

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

}

Guide to Java 8 groupingBy Collector, A guide to Java 8 groupingBy Collector with usage examples. The List of BlogPost objects: Let's also define a Tuple class that will be used to group posts by the combination of their type and author attributes:� Question: Tag: java,collections I am looking for a nice way to group a list of objects by multiple class attributes. The Google guava library provides a feature to group by a single attribute.

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

Group object by field name using java 8, Lets find out how group objects within java 8 just like you do with SQL. The list could go on to group objects by attributes into business� The Java 8 Stream API lets us process collections of data in a declarative way. The static factory methods Collectors.groupingBy() and Collectors.groupingByConcurrent() provide us with functionality similar to the ‘GROUP BY' clause in the SQL language. They are used for grouping objects by some property and storing results in a Map instance.

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

Java 8 – Stream Collectors groupingBy examples, List Objects. Examples to 'group by' a list of user defined Objects. 2.1 A Pojo. Item .java. package com.mkyong.java8; import java.math. As with all other objects, the cn of a group must be unique among the sibling objects in the container that contains the group. member: The member attribute is a multi-value attribute that contains the list of distinguished names for the user, group, and contact objects that are members of the group. Each item in the list is a linked reference

Multi level grouping with streams, With Java 8 streams it is pretty easy to group collections of objects based on different final Map<String, List<Person>> personsByCountry� Something like the first answer in this post: How to Group Objects in a List into other Lists by Attribute using streams & Java 8? UPDATE2 : Also, the timestamps are not necessarily every 5 minutes. They could be at random times and some intervals could have 3 or 5 rows in them.

Java 8 groupingBy Collector, It helps us group objects based on certain property, returning a Map as an outcome. In this article, we'll look at various example usages of the groupingBy collector in Java 8. In the examples that follow, we'll open our stream over this List of groupingBy to group our elements based on different attributes. Here is a REAL GROUP BY for Array of Objects by some field(s) with 1) calculated key name and 2) complete solution for cascading of grouping by providing the list of the desired keys and converting its unique values to root keys like SQL GROUP BY does.

Java Streams groupingBy Examples, Using Java Streams and Collectors is a good way to implement SQL functionality to your aggregations so you can group, sort, and summarize calculations. Have you wanted to perform SQL-like operations on data in a List or a Map? Maybe computing a sum or The value is the Player object. The output� Java List tutorial and examples for beginners. In this Java list tutorial, I will help you understand the characteristics of list collections, how to use list implementations (ArrayList and LinkedList) in day-to-day programming and look at various examples of common programming practices when using lists.

Comments
  • A hashmap with location as the key and the students list as value.
  • Would sorting by location solve your problem, or is there something else?
  • Try using Comparator and sort by location.
  • @Warlord Yes, But going further if I need get information like, Student count by Location better if I could get it grouped
  • @Omoro Please can you give me a clue by code, Im not so familiar with Hashmaps
  • You declared a List of Location objects and in the next line you add a Student object to the previous list which should throw an error.
  • hashMap.get() returns null when hashMap.contanisKey() return false. You could save the call to containsKey() method if you call first hashMap.get(), store result in a local var, and check if this local var is null
  • That is because in Student class stud_location is specified as Friendly. Only Student class and any class that is defined in the same package of Student can access stud_location. If you put public String stud_location; instead of String stud_location;, this should work. Or you can define a getter function. More info in cs.princeton.edu/courses/archive/spr96/cs333/java/tutorial/java/…
  • This answer can be improved by sticking to the same example as the question. Also the result does not match with the desired output requested in the question.
  • Hi, please don't post the same answer multiple times, and please don't post raw code without an explanation about how it works and how it solves the problem in the question above.
  • Sorry buddy, there was some mistake in pasting the code, since it might have become multiple times. I have edited explanation for what I posted. Hope that looks fine now???
  • I'm missing something or this code is sorting instead of grouping by a field? I see products sorted by ID, then by Price
  • beautiful! Thanks!
  • Why Sort ? The problem is to group the elements !