简体   繁体   中英

How do I store the key and value into hashmap and print it out accordingly?

Currently, I am retrieving data from a csv file and storing the data into a hashmap. However, when I print out the content of the hashmap, it is not in the order that I thought it would be. How do I format the hashmap such that it would print in the order of dec -> jan -> feb ?

CODE

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

CURRENT OUTPUT

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

DESIRED OUTPUT

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

You can use linked hash map which maintain the order of insertion

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

output->

{one=1, two=2,four=3}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM