gpt4 book ai didi

java - 如何根据日期格式化数据

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

如何根据日期格式化数据

我正在使用 TreeMap 并希望根据日期排序

我有一个人员列表,我想根据出生日期进行排序

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;

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", 21, "01/01/1981"));
personList.add(new Person("John", "London", 21, "01/02/1981"));
personList.add(new Person("Prasanna", "London", 23, "04/28/1990"));
personList.add(new Person("Monobo", "Tokyo", 23, "04/28/1990"));
personList.add(new Person("Sam", "Paris", 23, "07/12/1992"));
personList.add(new Person("Nadal", "Paris", 31, "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) {
Date inputDate = simpleDateFormatInput.parse(p.getDateOfBirth());

String outPutDate = simpleDateFormatOutput.format(inputDate);

if (!personByMap.containsKey(outPutDate)) {
personByMap.put(outPutDate, new ArrayList<>());
}

personByMap.get(outPutDate).add(p);

}

System.out.println(personByMap);


} 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;
}

public Person(String name, String city, int age, String dateOfBirth) {
this.name = name;
this.city = city;
this.age = age;
this.dateOfBirth = dateOfBirth;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Person [name=" + name + ", city=" + city + ", age=" + age + "]";
}
}

最佳答案

您所需要的只是为仅比较出生日期的人定制比较器。

Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
//access your formatter simpleDateFormatInput here.
return simpleDateFormatInput.format(o1.dateOfBirth).compareTo(simpleDateFormatInput.format(o2.dateOfBirth));
}
});

关于java - 如何根据日期格式化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57218742/

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