Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert map to string using java 8 lambda [duplicate]

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

like image 748
BudsNanKis Avatar asked Aug 14 '26 05:08

BudsNanKis


1 Answers

This can be done using the joining collector:

String str = map.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
                                    .collect(Collectors.joining(","));
like image 80
Joe C Avatar answered Aug 16 '26 18:08

Joe C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!