gpt4 book ai didi

java - 如何将键和值存储到 hashmap 中并相应地打印出来?

转载 作者:行者123 更新时间:2023-12-02 08:59:22 25 4
gpt4 key购买 nike

目前,我正在从 csv 文件中检索数据并将数据存储到 HashMap 中。但是,当我打印出 HashMap 的内容时,它的顺序与我想象的不同。如何格式化 HashMap ,使其按照 dec -> jan -> feb 的顺序打印?

代码

public static void main(String[] args) throws ParseException {
//readXLSXFile("C:\\Users\\User\\Desktop\\AllSgStuffdata2.xlsx");
HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
int febCounter = 0;
int janCounter = 0;
int decCounter = 0;
String pattern = "MMM";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);

try (Reader reader = Files.newBufferedReader(Paths.get("file_path"));
CSVReader csvReader = new CSVReader(reader);){
String [] nextRecord;
while((nextRecord = csvReader.readNext()) != null) {
//Date date = sdf.parse(nextRecord[2]);
//System.out.println(date);
String retrievedate = nextRecord[2];
Date date = sdf.parse(retrievedate);
String strDate = sdf.format(date);
//System.out.println(strDate);

if(strDate.equals("Dec")) {
decCounter++;
}
else if (strDate.equals("Jan")) {
janCounter++;
}
else if (strDate.equals("Feb")) {
febCounter++;
}
}
numberOfPost.put("December", decCounter);
numberOfPost.put("January", janCounter);
numberOfPost.put("Feburary", febCounter);
System.out.println(numberOfPost);
} catch(IOException | ParseException e) {
System.out.print("File can't be found");
}
}

电流输出

{Feburary=365, December=303, January=582}

期望输出

{December=303, January=582, Feburary=365}

最佳答案

您可以使用链接 HashMap 来维护插入顺序

 LinkedHashMap<String, String> lhm = 
new LinkedHashMap<String, String>();
lhm.put("one", "1");
lhm.put("two", "2");
lhm.put("four", "3");
System.out.println(lhm);

输出->

{一=1,二=2,四=3}

关于java - 如何将键和值存储到 hashmap 中并相应地打印出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60275079/

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