Stream Only inputting the last line from Files.lines()

In my code I have

Files.lines(Paths.get(fileName), Charset.forName("Cp1252"))
                .filter(k -> k != "")
                .forEach(m -> hashmap.put(LocalDateTime.MIN, m));

To read the lines from a file called “info” (fileName).

1
2
3
4
5
(blank line)

However, when scanning the HashMap it tells me that only the last line has been inserted using this code:

int x = 0;
for (HashMap.Entry<LocalDateTime, String> s : hashmap.entrySet()) {
    x++;
    System.out.println(hashmap.size() + ": " + x + ": " + s.getValue());
}

That prints out 1: 1: 5 only once.

Answer

The problem is that your code snippet puts all lines under the same key into the HashMap. This code

.forEach(m -> hashmap.put(LocalDateTime.MIN, m));

takes each line from the file, and puts it at the key equal to LocalDateTime.MIN. Since HashMap cannot contain multiple identical keys, the last item is the only one remaining in the map after forEach finishes.

To fix this problem choose a different container, such as a list, or use a different strategy of assigning keys to lines that you read from the file.

Leave a Reply

Your email address will not be published. Required fields are marked *