简体   繁体   中英

How to remove “{” in HashMap java

when i am using HashMap the output is always like this {a,2}, instead of that i want an output like (a,2). How can i delete the curly bracket or modify it to ")" this.

wordCount.put("("+'"'+splitted[i].toLowerCase()+'"'+")",

wordCount.getOrDefault(splitted[i], 0) + 1);    

and the ouput is

{("the")=1, ("be")=1, ("like")=1}

,but i want an output like this,

( “the” , 132 )

Thanks.

Rather than using the built-in toString method you should implement your own if you want a customised representation.

For example (using Java 8):

String toFormattedString(Map<String,Integer> map) {
    return map.entrySet().stream()
        .map(e -> String.format("(\"%s\", %d)", e.getKey(), e.getValue()))
        .collect(Collectors.joining(", "));
}

This way you can make the formatted output exactly as you want it to be, with the keys in the order you want etc.

Did you try to replace the characters using String#replace ?

String s = "(" + myHashMap.toString().replace("{", "").replace("}", "") + ")";
System.out.println(s); // (the=132)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM