2014年9月24日 星期三

Java:convert List/Map to a join string

There's no such convenience method in the standard Java API.
But, All the references to Apache Commons are fine.
Use the library 「org.apache.commons.lang.StringUtils」.

List:
  List<String> list = Arrays.asList("342443","342450","342449");
  System.out.println(StringUtils.join(list, ","));
  // 342443,342450,342449

Map:
  Map<String, Integer> map = new HashMap<String, Integer>();
  map.put("342443", 23);
  map.put("342450", 672);
  map.put("342449", 15);
  // join keys
  System.out.println(StringUtils.join(map.keySet(), ","));
  // 342443,342450,342449

  // join valus
  System.out.println(StringUtils.join(map.values(), ","));
  // 23,672,15

沒有留言: