Convert hashmap to string java

How to convert a HashMap to a K/V-String in Java 8 with Streams

Is there any faster, better code to do that? It seems to be costly to append the keys and Values in the map function, doesn’t it?

I would not worry about performance in this case unless it’s a critical part of the system and it’s pointed out as a bottleneck by usage of a profiler or a similar tool. If you haven’t done this before and you think this code is not optimal, then I̶ ̶k̶n̶o̶w̶ ̶t̶h̶a̶t̶ maybe you’re wrong and should test it first.

Please note that in JDK 9 StringJoiner (which is the underlying class for Collectors.joining ) was optimized, thus stream implementation will work about 20-25% faster than in JDK 8 (though still not as fast as naive).

3 Answers 3

map -> map.entrySet().stream().map(Entry::toString).collect(joining(";", "[", "]")) 

(Note that I omitted the imports.)

I would not worry about performance in this case unless it’s a critical part of the system and it’s pointed out as a bottleneck by usage of a profiler or a similar tool. If you haven’t done this before and you think this code is not optimal, then I̶ ̶k̶n̶o̶w̶ ̶t̶h̶a̶t̶ maybe you’re wrong and should test it first.

OP’s ‘Collectors.joining()’ call had the delimiter, prefix, suffix misordered. Your solution fixed that.

Note that while Entry.toString() usually returns key = value , it’s not explicitly required by the Entry interface, thus you may hit the map implementation which returns something else. I’d prefer explicit concatenation like in the question.

Читайте также:  Read php session file

I have looked at Entry interface. I could not fine any declaration toString . Could you give explain how Entry::toString() define ? Another thing, only Entry::toString can not resolve in my end. I need to do Map.Entry::toString() .

@seal toString() is declared by java.lang.Object , so it’s inherited by everything. If you do import java.util.Map.Entry; , then you can use Entry::toString directly.

Use StringBuilder instead of buffer.

Javadoc => Class StringBuffer

«The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.» Class StringBuffer

While using StringBuilder may be faster than StringBuffer for the first piece of code, the question is specifically about the speed of the second piece of code, as @LuiggiMendoza points out.

And for readers, the compiler create a StringBuilder in second case for this piece of code: entry.getKey() + » = » + entry.getValue()) on every iteration, so there’s no need to use another StringBuilder . And Collectors#joining will use a StringJoiner that uses a StringBuilder behind the scenes for you, I guess there’s no real improvement using a StringBuilder at all.

Источник

Java HashMap content to String [duplicate]

Please read comments before You downmark! I want convert content of HashMap to String as converting ArrayList to String using Arrays.toString(arrayList) . Is it possible ? There is easy way to do this? Do I must have to iteration and appending it using Iterator ? As example:

HashMap> objectMap = new HashMap>(); //. put many items to objectMap Iterator it = objectMap.entrySet().iterator(); while(it.hasNext()) < Map.Entry pairs = (Map.Entry) it.next(); System.out.println(pairs.getKey() + " mt24 mb12">
    javahashmap
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this question
)">edited Feb 24, 2016 at 8:43
asked Feb 24, 2016 at 8:10
0
Add a comment|

1 Answer 1

Reset to default
10

You can use toString() of the Map:

String content = objectMap.toString();

Map overrides the toString() method, so you can easily get the contents of map. I should give an example: public static void main(String[] args) throws Exception < HashMap> objectMap = new HashMap<>(); List list = new ArrayList<>(); list.add(new MyObject(12, 12)); objectMap.put("aaaa", list); String content = objectMap.toString(); System.out.println("content = " + content); > private static class MyObject < int min; int max; public MyObject(int max, int min) < this.max = max; this.min = min; >@Override public String toString() < return "MyObject

Источник

Convert HashMap to string comma separated

Its printed like com.android.test@34566f3,com.android.test@29f9042 How do I print data on Map to string (human readable)?

5 Answers 5

Make your Product class overriding the toString() method or in your custom logic, make a string builder appending not the element itself, but it's fileds, which you wish to recieve as text description of the product instance. I mean something like this:

//since I don't know, what is the Product class, I supposed it has a name filed commaSepValueBuilder.append(mCartList.get(i).getName()); 

Don't use Vector , use ArrayList . Quoting javadoc:

If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector

The shorter version of getCartList() is:

public static List getCartList() < return new ArrayList<>(cartMap.keySet()); > 

As for how to build comma-separated list of products, the best way is to implement the Product method toString() . This will also help when debugging.

Then you can use StringBuilder in a simple for-each loop:

StringBuilder buf = new StringBuilder(); for (Product product : ShoppingCartHelper.getCartList()) < if (buf.length() != 0) buf.append(", "); buf.append(product); // or product.getName() if you didn't implement toString() >System.out.println(buf.toString()); 

In Java 8 that can be simplified by using StringJoiner :

StringJoiner sj = new StringJoiner(", "); for (Product product : ShoppingCartHelper.getCartList()) sj.add(product); System.out.println(sj.toString()); 

You can override toString method in your Product class like below,

public class Product < //sample properties private String name; private Long id; public String getName() < return name; >public void setName(String name) < this.name = name; >public Long getId() < return id; >public void setId(Long id) < this.id = id; >@Override public String toString() < return "Product 
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Nov 17, 2015 at 4:20
Add a comment |
0

Override toString in Product class and use Java 8 Streams to make it more simpler, as below:

 mCartList.stream().map(e -> e.toString()) .collect(Collectors.joining(",")); 
List mCartList = new ArrayList<>(); mCartList.add(new Product(1, "A")); mCartList.add(new Product(2, "B")); String commaSepValue = mCartList.stream().map(e -> e.toString()) .collect(Collectors.joining(",")); System.out.println(commaSepValue); 
final class Product < private final int id; private final String name; public Product(int id, String name) < this.id = id; this.name = name; >public String getName() < return name; >public int getId() < return id; >@Override public String toString() < return "Product [id=" + id + ", name=" + name + "]"; >> 

Источник

Оцените статью