共計 637 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,使用 Stream 的 groupBy 方法可以對 Stream 中的元素進行分組操作。groupBy 方法接受一個 Function 作為參數,該函數用于提取元素的鍵值,并返回一個 Map 對象,其中鍵是分組的值,值是屬于該分組的元素列表。
示例如下:
假設有一個包含 Person 對象的 List,每個 Person 對象有一個 age 屬性,我們想按照 age 屬性進行分組:
List<Person> persons = Arrays.asList(new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25),
new Person("David", 30)
);
Map<Integer, List<Person>> groupedByAge = persons.stream()
.collect(Collectors.groupingBy(Person::getAge));
groupedByAge.forEach((age, people) -> {System.out.println("Age " + age + ": " + people);
});
在這個例子中,我們首先使用 stream 方法將 List 轉換為 Stream,然后使用 collect 方法和 groupingBy 方法進行分組操作。最后,我們通過 forEach 方法遍歷每個分組,并輸出結果。
注意:在上面的例子中,Person 類需要實現一個 getAge 方法來獲取年齡屬性。
丸趣 TV 網 – 提供最優質的資源集合!
正文完