1

I wonder if it is possible to read a text file with the following strucutre

1946-01-12;07:00:00;-1.3;G
1946-01-12;13:00:00;0.3;G
1946-01-12;18:00:00;-2.8;Y
1946-01-13;07:00:00;-6.2;G
1946-01-13;13:00:00;-4.7;G
1946-01-13;18:00:00;-4.3;Y
1946-01-14;07:00:00;-1.5;G

but with more lines to a hashmap where the dates are keys and and the values are -1.3, 0.3, -2.8, -6.2... and so on? Is it possible even though there are multiples of the same date to store many values in the same date/key?

Natalie_94
  • 79
  • 3
  • 12
  • What are the `G`s and `Y`s doing? – Sweeper Mar 08 '20 at 21:09
  • They just represent quality codes. I just want to store the values -1.3, 0.3, -2.8 in the first date, the values -6.2, -4.7, -4.3 in the next date and so on. @Sweeper – Natalie_94 Mar 08 '20 at 21:13
  • You can check this [SO post](https://stackoverflow.com/a/34020700/8963486) and modify it on your needs. – Noohone Mar 08 '20 at 21:15
  • 2
    Okay, this is a problem that consists of multiple parts. Which part are you stuck on? Reading the file? Splitting each line into date and number? Putting them into the map? – Sweeper Mar 08 '20 at 21:15
  • I have already read the file to an array and parsed the data. So I saved the dates and values in different variables. So I guess my problem is how to put it into a map. @Sweeper – Natalie_94 Mar 08 '20 at 21:37
  • Create a custom bean which should store 1.3 and Y type of value in different variables. Now create Map> mapObj. As a key you can pass Date value. In you case same key contains multiple value you can initialize list and put the values if the key is not found otherwise get the list and update it based on Date as key – Harsh Kanakhara Mar 08 '20 at 22:03

1 Answers1

3

This answer assumes that your file contains no duplicate keys, and the file format does not need validation.

You should use a Map<LocalDateTime, Double>, Map<LocalDate, Double> to store your data, depending on whether you want the time part or not:

Map<LocalDateTime, Double> map = new HashMap<>();

Suppose we are in a loop that reads the file line by line until the end of the file, the line that has been just read is stored in the string line, we can parse the line like this:

String[] parts = line.split(";");

// the dates and times are all in ISO8601 format, so we can call "parse" directly
LocalDate date = LocalDate.parse(parts[0]);
LocalTime time = LocalTime.parse(parts[1]);
double number = Double.parseDouble(parts[2]);
LocalDateTime dateTime = LocalDateTime.of(date, time);

Now we can put it in the map:

map.put(dateTime, number);

LocalDateTime and LocalDate implement hashCode and equals, so we don't need to worry about that at all.

Sweeper
  • 213,210
  • 22
  • 193
  • 313