Home > Java > javaTutorial > body text

How to Group Java Objects by an Attribute Using Collectors.groupingBy()?

DDD
Release: 2024-11-23 14:06:15
Original
911 people have browsed it

How to Group Java Objects by an Attribute Using Collectors.groupingBy()?

How to Group Objects by an Attribute in Java

Grouping objects by a specific attribute is a common operation in programming. To do this, you can use the Collectors.groupingBy() method in Java 8.

Consider the following code, which creates a list of Student objects and stores them in a list:

public class Grouping {
    public static void main(String[] args) {

        List<Student> studlist = new ArrayList<>();
        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"));

    }
}

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;
    }
}
Copy after login

To group the Student objects by their location, you can use the following code:

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

This code uses the Collectors.groupingBy() method to group the Student objects by their stud_location attribute. The result is a Map that contains the location as the key and a List of Student objects as the value.

This approach provides a clean and concise way to group objects by an attribute in Java 8.

The above is the detailed content of How to Group Java Objects by an Attribute Using Collectors.groupingBy()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template