user8826109
user8826109

Reputation:

Write text to a file in Java

I'm trying to write a simple output to a file but I'm getting the wrong output. This is my code:

Map<Integer,List<Client>> hashMapClients = new HashMap<>();
hashMapClients = clients.stream().collect(Collectors.groupingBy(Client::getDay));

Map<Integer,List<Transaction>> hasMapTransactions = new HashMap<>();
hasMapTransactions = transactions.stream().collect(Collectors.groupingBy(Transaction::getDay));

//DAYS
String data;
for (Integer key: hashMapClients.keySet()) {
    data = key + " | ";
    for (int i = 0; i <hashMapClients.get(key).size();i++) {
        data += hashMapClients.get(key).get(i).getType() + " | " + hashMapClients.get(key).get(i).getAmountOfClients() + ", ";
        writer.println(data);
    }
}

I get this output

1 | Individual | 0,

1 | Individual | 0, Corporation | 0,

2 | Individual | 0,

2 | Individual | 0, Corporation | 0,

But it should be, also it should not end with , if it's the last one.

1 | Individual | 0, Corporation | 0
2 | Individual | 0, Corporation | 0

What am I doing wrong?

Upvotes: 0

Views: 75

Answers (2)

erickson
erickson

Reputation: 269877

One problem is that you are calling println after every Client, rather than waiting until the whole list is built. Then, to fix the problem with the trailing comma, you can use a joining collector.

Map<Integer,List<Client>> clientsByDay = clients.stream()
  .collect(Collectors.groupingBy(Client::getDay));
/* Iterate over key-value pairs */
for (Map.Entry<Integer, List<Client>> e : clientsByDay) {
    /* Print the key */
    writer.print(e.getKey());
    /* Print a separator */
    writer.print(" | ");
    /* Print the value */
    writer.println(e.getValue().stream()
      /* Convert each Client to a String in the desired format */
      .map(c -> c.getType() + " | " + c.getAmountOfClients())
      /* Join the clients together in a comma-separated list */
      .collect(Collectors.joining(", ")));
}

Upvotes: 0

David
David

Reputation: 219096

It sounds like you only want to write data to the output in the outer loop, not the inner loop. The latter of which is just for building the data value to write. Something like this:

String data;
for (Integer key: hashMapClients.keySet()) {
    // initialize the value
    data = key + " | ";

    // build the value
    for (int i = 0; i <hashMapClients.get(key).size();i++) {
        data += hashMapClients.get(key).get(i).getType() + " | " + hashMapClients.get(key).get(i).getAmountOfClients() + ", ";
    }

    // write the value
    writer.println(data);
}

Edit: Thanks for pointing out that the last character also still needs to be removed. Without more error checking, that could be as simple as:

data = data.substring(0, data.length() - 1);

You can add error checking as your logic requires, perhaps confirming that the last character is indeed a comma or confirming that the inner loop executes at least once, etc.

Upvotes: 2

Related Questions