Home >Java >javaTutorial >How to Group Java Objects by Attributes Using Streams?

How to Group Java Objects by Attributes Using Streams?

Susan Sarandon
Susan SarandonOriginal
2024-11-18 05:33:02438browse

How to Group Java Objects by Attributes Using Streams?

Grouping Objects by Attributes using Java Streams

As you've mentioned, you want to group a list of objects by an attribute called "Location." Here's a clean way to achieve this using Java 8's streams:

import java.util.*;
import java.util.stream.Collectors;

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

        // Group the list by "Location" attribute using Streams
        Map<String, List<Student>> studlistGrouped =
                studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

        // Print the results
        for (String location : studlistGrouped.keySet()) {
            System.out.println("Location: " + location);
            for (Student student : studlistGrouped.get(location)) {
                System.out.println("\t" + student.stud_id + " " + student.stud_name);
            }
        }
    }

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

This program uses the Collectors.groupingBy() method of the Streams API to group the students by their locations. The resulting map (studlistGrouped) contains keys as locations and values as lists of students in that location.

The above is the detailed content of How to Group Java Objects by Attributes Using Streams?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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