gpt4 book ai didi

java - 怎样总结年代?

转载 作者:行者123 更新时间:2023-12-02 02:32:56 24 4
gpt4 key购买 nike

这是我的程序

package com;        
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.google.gson.Gson;

public class GroupByDemoInJava8 {
public static void main(String args[]) throws Exception {
try {
List<Person> personList = new ArrayList<>(); // Date Format is MM/DD/YYYY
personList.add(new Person("Mike", "London", 15, "01/01/1981"));
personList.add(new Person("John", "London", 21, "01/02/1981"));
personList.add(new Person("Prasanna", "London", 28, "04/28/1990"));
personList.add(new Person("Monobo", "Tokyo", 34, "04/28/1990"));
personList.add(new Person("Sam", "Paris", 44, "07/12/1992"));
personList.add(new Person("Nadal", "Paris", 5, "04/02/1992"));
String patternInput = "MM/dd/yyyy";
SimpleDateFormat simpleDateFormatInput = new SimpleDateFormat(patternInput);
String outputPattern = "MMM-yy";
SimpleDateFormat simpleDateFormatOutput = new SimpleDateFormat(outputPattern);
Map<String, List<Person>> personByMap = new TreeMap<String, List<Person>>();

for (Person p : personList) {
int sumAge = 0;
Date inputDate = simpleDateFormatInput.parse(p.getDateOfBirth());

String outPutDate = simpleDateFormatOutput.format(inputDate);

if (!personByMap.containsKey(outPutDate)) {
sumAge = sumAge+p.getAge();
System.out.println("Date "+outPutDate+" "+"Age "+sumAge);
}

else
{
personByMap.get(outPutDate).add(p);
}

}



} catch (Exception e) {
e.printStackTrace();
}

}
}

最佳答案

类似这样的事情

public class GroupByDemoInJava8 {
public static void main(String args[]){
List<Person> personList = new ArrayList<>();
/* INITIALIZATION */
Map<String, Integer> result = personList.stream()
.collect(Collectors.groupingBy(Person::getDateOfBirth,
Collectors.summingInt(Person::getAge));
}
}

如上所述here

关于java - 怎样总结年代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57220323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com