2

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Rob
  • 88
  • 1
  • 14

1 Answers1

3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Any chance you know how to I could do an iteration counter in this format so I can set them as different keys? – Rob Jun 25 '15 at 00:25
  • 2
    @Rob Unfortunately, Java does not offer an easy way of doing it ([here is a relevant Q&A](http://stackoverflow.com/q/18552005/335858)). You could use some of the tricks from that Q&A, but it's not ideal. – Sergey Kalinichenko Jun 25 '15 at 00:32
  • AtomicInteger worked. It's sloppy, but it works. Thanks! – Rob Jun 25 '15 at 00:50