如何使用流按屬性對 Java 物件進行分組?
Nov 18, 2024 am 05:33 AM使用 Java Streams 將物件依屬性分組
如您所提到的,您希望以名為「位置」的屬性對物件清單進行分組。以下是使用 Java 8 的串流實現此目的的簡潔方法:
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; } } }
登入後複製
程式使用 Streams API 的 Collectors.groupingBy() 方法按學生的位置將學生分組。產生的地圖 (studlistGrouped) 包含作為位置的鍵和作為該位置的學生清單的值。
以上是如何使用流按屬性對 Java 物件進行分組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

2025年的前4個JavaScript框架:React,Angular,Vue,Svelte

如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?

Spring Boot Snakeyaml 2.0 CVE-2022-1471問題已修復
