如您所提到的,您希望以名為「位置」的屬性對物件清單進行分組。以下是使用 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中文網其他相關文章!