Home » Java » java – How do I store the key and value into hashmap and print it out accordingly?-Exceptionshub

java – How do I store the key and value into hashmap and print it out accordingly?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

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}
How to&Answers:

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}