Home > Java > javaTutorial > How Can I Group Objects by an Attribute Using Java 8 Streams?

How Can I Group Objects by an Attribute Using Java 8 Streams?

Linda Hamilton
Release: 2024-11-23 10:01:27
Original
258 people have browsed it

How Can I Group Objects by an Attribute Using Java 8 Streams?

Grouping Objects by an Attribute Using Java 8

In Java, grouping objects by an attribute can provide a structured way to organize and analyze data. For example, suppose you have a list of students and their locations. You may wish to group the students based on their location for further processing.

Here's a snippet of code that leverages the advanced features of Java 8 to achieve this:

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
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"));

        Map<String, List<Student>> studlistGrouped =
            studlist.stream().collect(Collectors.groupingBy(w -> w.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;
    }
}
Copy after login

The Collectors.groupingBy method, introduced in Java 8, allows you to create a Map that groups objects based on the value of a specified key function. In this case, we specify the stud_location field as the key function, resulting in a map where each key represents a location and the corresponding value is a list of students at that location.

This approach provides an efficient and elegant way to group a list of objects using a specific attribute. The resulting Map can be leveraged for various purposes, such as further filtering, sorting, or data visualization.

The above is the detailed content of How Can I Group Objects by an Attribute Using Java 8 Streams?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template