在此示例中,它根据整个日期对数据进行分组。我们可以仅根据月份和年份对数据进行分组吗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
提交
取消