Search code examples
javahashmapreadfilelocaldatedatetimeformatter

How to populate a HashMap with data from a txt file


I need to put the following dates from Dates.txt file into a HashMap.

1 05.05.2017
2 11.12.2018
3 05.30.2020
4 03.15.2011
5 12.15.2000
6 10.30.2010
7 01.01.2004
8 12.31.1900
9 02.28.2014
10 10.10.2012

The format for the HashMap should be

Initial Hashmap:

2017-05-05:1
2018-11-12:2
2020-05-30:3
2011-03-15:4
2000-12-15:5
2010-10-30:6
2004-01-01:7
1900-12-31:8
2014-02-28:9
2012-10-10:10

My code snippet so far

public class driver {
    public static void main(String[] args) throws FileNotFoundException {
        HashMap <LocalDate, Integer> dates = new HashMap <LocalDate, Integer>();
        Scanner s = new Scanner(new File("Dates.txt")); 
        while(s.hasNext())
        {
           dates.put(LocalDate.parse("mm.dd.yyyy"), Integer);
        }   

        System.out.println(dates);
    }
}

I am having trouble figuring out what to put in my dates.put(key,value) line of code so the HashMap is formatted as above. I'm not sure if it'd be better to read the txt file into an ArrayList then using put() to populate the HashMap. Any guidance or answers would be appreciated!


Solution

  • From the given data, it looks like there's no really reason to use a map - as you noted, you've struggled to find an appropriate value. You could accumulate them in to an ArrayList, or even a HashSet if the order isn't important instead.