我希望代码得到这个输出:lee [2],rebok [2];

时间:2014-01-11 10:49:22

标签: java

ArrayList arrayList = new ArrayList();
arrayList.add("lee");
arrayList.add("lee");
arrayList.add("rebok");
arrayList.add("rebok");

Set set = new LinkedHashSet(arrayList);

我希望代码能够获得此输出:

lee[2],rebok[2];

1 个答案:

答案 0 :(得分:0)

使用guava Multiset进行计数

final StringBuilder out = new StringBuilder();
final Multiset<String> count = HashMultiset.create(arrayList); // your arraylist
for (final String key : count.elementSet()) {
    out.append(key).append('[').append(count.count(key)).append("],");
}
// we need to remove a possible trailing comma
System.out.println(out.length() > 0 ? out.substring(0, out.length() - 1) : "");

输出:

lee[2],rebok[2]