2

I want to Convert a map {key:column, key1:column1} to a csv string "key=column,key1=column".

I am getting the entry map and constructing the string out of key and value. Here's what I have:

        entry.forEach(entryVal ->{
            result.append(entryVal.getKey() + "=" + entryVal.getValue());
            result.append(',');
        });
        int index = result.lastIndexOf(",");
        if(index == result.length()-1){
            result.deleteCharAt(index);
            return result.toString();
        }

Sure, looks ugly, especially I have to do postprocessing on the comma. Wondering if there is a cleaner way of doing this?

Note: I do not need a code review, just need to know a different but cleaner way of writing the same thing if at all possible

Shawn Mehan
  • 4,513
  • 9
  • 31
  • 51
BudsNanKis
  • 224
  • 5
  • 17

2 Answers2

8

This can be done using the joining collector:

String str = map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
                                    .collect(Collectors.joining(","));
Joe C
  • 15,324
  • 8
  • 38
  • 50
1

Don't over complicate it:

String str = map.toString().replace(":", "=").replaceAll("^.|.$", "");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • .replaceAll(",","\n"); – acpuma May 30 '19 at 22:19
  • 1
    @acpuma the accepted answer, like mine, separates with commas, which OP asked for – Bohemian May 30 '19 at 23:10
  • this solution depends on the exact format of the toString() output for the map, which is not a guaranteed part of the Map interface specification – Michael Lucas May 21 '20 at 20:05
  • @MichaelLucas The implementation of `toString()` hasn't changed since the first java version, which was over 25 years ago. I am willing to wager a very large sum of money that it won't ever change. But even if it did, your unit tests would catch any such problem. – Bohemian May 22 '20 at 00:01
  • @Bohemian because Map is an interface, it doesn't have any guaranteed toString() implementation. You may be right that HashMap's toString() is unlikely to change, but code should be made to work reliably regardless of the implementation. Note that the first version of java did not include Map or HashMap at all (those were the days of Vectors and Hashtables). – Michael Lucas May 24 '20 at 04:40
  • @m sure from a theoretical view, but at a practical level, this code is going to work every time and forever for all Map implementations from the JDK, which are the only ones people use in practice. If you don’t believe this code is reliable, and you would like to make some money, I would happily engage in a formal wager of say $USD10K that is still works in 5 years - let me know. – Bohemian May 24 '20 at 04:49