将HashMap转换为逗号分隔的字符串

4
我有一个名为 ShoppingCartHelper 的类和一个方法。
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();

存储产品数据到购物车存储器(cartMap)的方法:

public static List<Product> getCartList() {
    List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
    for(Product p : cartMap.keySet()) {
        cartList.add(p);
    }
    return cartList;
}

在另一个类中,我使用map来调用存储的数据:
private List<Product> mCartList;
mCartList = ShoppingCartHelper.getCartList();

并以逗号分隔的形式将其打印出来:
StringBuilder commaSepValueBuilder = new StringBuilder();
for ( int i = 0; i< mCartList.size(); i++) {
   commaSepValueBuilder.append(mCartList.get(i));
   if ( i != mCartList.size()-1) {
       commaSepValueBuilder.append(", ");
   }
}
System.out.println(commaSepValueBuilder.toString());

它的打印格式为 com.android.test@34566f3,com.android.test@29f9042

如何将Map中的数据转换成字符串(人类可读)?

5个回答

3

让你的Product类重写toString()方法或者在你的自定义逻辑中,创建一个字符串构建器来添加不是元素本身,而是其字段,这些字段是你希望作为产品实例的文本描述接收到的。我的意思是像这样:

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

2
不要使用Vector,使用ArrayList。引用javadoc:
如果不需要线程安全实现,建议使用ArrayList代替Vector。
getCartList()的简短版本为:
public static List<Product> getCartList() {
    return new ArrayList<>(cartMap.keySet());
}

关于如何构建逗号分隔的产品列表,最好的方法是实现Product方法toString()。这也有助于调试。

public class Product {

    // lots of code here

    @Override
    public String toString() {
        return getName(); // Assuming Product has such a method
    }
}

那么你可以在简单的for-each循环中使用StringBuilder

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());

在Java 8中,可以使用StringJoiner来简化这个过程:StringJoiner
StringJoiner sj = new StringJoiner(", ");
for (Product product : ShoppingCartHelper.getCartList())
    sj.add(product);
System.out.println(sj.toString());

0
您可以像下面这样覆盖您的Product类中的toString方法:
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{" +
            "name='" + name + '\'' +
            ", id=" + id +
            '}';
}

}

它可以以人类可读的格式打印字符串。


0

在Product类中覆盖toString方法,并使用Java 8 Streams使其更简单,如下所示:

 mCartList.stream().map(e -> e.toString())
                .collect(Collectors.joining(","));

使用方法:

List<Product> 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);

Product.java

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 + "]";
        }
    }

0
以下代码对我有效,使用Java 8 Streams:

对于Hashmap:

hashmapObject.entrySet().stream().map(e -> e.toString())
                .collect(Collectors.joining(","));

关于列表:

listObject.stream().map(e -> e.toString())
                .collect(Collectors.joining(","));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接