1

I got the file with following structure:

MES2018-05-24_12:05:58.778 RGH2018-05-24_12:06:27.441 ... PGS2018-05-24_12:08:36.586

Want to parse it into Map with key containing only first three symbols of input string, something like this:

MES=12:05:58.778

But IDE won't compile the code provided below. Is there any right way to do this using stream API?

public Map<String, Date> read(String filePath) {
        SimpleDateFormat sdt = new SimpleDateFormat("HH:mm:ss.SSS");
        Map<String, Date> mapFromFile = null;
        try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
            mapFromFile = stream
                    .map(key ->  key.split("_"))
                    .collect(Collectors.toMap(value -> value[0].replaceAll("[^a-zA-Z]", ""), value -> sdt.parse(value[1])));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mapFromFile;
    }
  • 1.`Map mapFromFile = new HashMap<>()` 2. `sdt.parse` would throw a `ParseException` – Naman Sep 17 '19 at 01:56
  • Follow the [Java-8 way of converting a string to date](https://stackoverflow.com/a/4216767/1746118) from the answer and you would possibly get rid of the pain of `ParseException` there. – Naman Sep 17 '19 at 02:07
  • You should print out the value which caused ParseException. Maybe the file has unexpected string. – sulin Sep 17 '19 at 02:05

1 Answers1

1

Since you are on java 8 use enhanced Features, use DateTimeFormatter to parse String into Localtime and also use LocalTime instead of util.Date

public Map<String, LocalTime> read(String filePath) {

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
    try (Stream<String> stream = Files.lines(Paths.get(filePath))) {

        return stream.map(str -> str.split("_")).collect(
                Collectors.toMap(key -> key[0].substring(0, 3), val -> LocalTime.parse(val[1], formatter)));

    } catch (IOException e) {
        e.printStackTrace();
    }
    return new HashMap<>();
}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • `mapFromFile` is no more required in the code and `return new HashMap<>()` could be inferred as the last statement as well. – Naman Sep 17 '19 at 05:19