我们可以在 Java 8 中仅根据月份和年份对数据进行分组吗

在此示例中,它根据整个日期对数据进行分组。


我们可以仅根据月份和年份对数据进行分组吗


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;

            }



米琪卡哇伊
浏览 70回答 1
1回答

子衿沉夜

而不是使用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())));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java