在此示例中,它根據整個日期對數據進行分組。我們可以僅根據月份和年份對數據進行分組嗎package com; import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.stream.Collectors;import com.google.gson.Gson; public class GroupData { public static void main(String args[]) throws Exception { try { List<Person> personList = new ArrayList<Person>(); // Date Format is MM/DD/YYYY personList.add(new Person("Mike", "London", 35, "01/01/1981")); personList.add(new Person("John", "London", 21, "01/02/1981")); personList.add(new Person("John", "Bristol",41, "01/06/1981")); personList.add(new Person("Steve", "Paris",34, "03/07/2019")); Map<LocalDate, List<Person>> personByMap = new HashMap<>(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy"); personByMap = personList.stream() .collect(Collectors.groupingBy(p -> LocalDate.parse(p.getDateOfBirth(), dtf))); System.out.println(personByMap.size()); } catch (Exception e) { e.printStackTrace(); } } } class Person { private String name; private String city; private int age; private String dateOfBirth; public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; }
1 回答

子衿沉夜
TA貢獻1828條經驗 獲得超3個贊
而不是使用LocalDate
,使用YearMonth
:
personByMap = personList.stream()
? ? ? ? ? ? .collect(Collectors.groupingBy(p -> YearMonth.parse(p.getDateOfBirth(), dtf)));
我還建議您直接將出生日期存儲為LocalDate:
class Person {
? ? private String name;
? ? private String city;
? ? private int age;
? ? private LocalDate dateOfBirth;
? ? // ...
}
然后你可以這樣做:
personByMap = personList.stream()
? ? ? ? ? ? .collect(Collectors.groupingBy(p -> YearMonth.from(p.getDateOfBirth())));
添加回答
舉報
0/150
提交
取消