在此示例中,它根据整个日期对数据进行分组。
我们可以仅根据月份和年份对数据进行分组吗
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;
}
子衿沉夜
相关分类