正如您所提到的,您希望按名为“位置”的属性对对象列表进行分组。下面是使用 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中文网其他相关文章!