我有一个像这样的API键:
String mainUrl = "http://smshorizon.co.in/api/sendsms.php?";"&mobile= MOBILE_NUMBER1, MOBILE_NUMBER2, MOBILE_NUMBER3";
我想将多个手机号码作为逗号分隔值添加到键("&mobile="
)。我尝试使用带有列表的hasp映射,但问题是它将值添加为数组,因为它是一个集合。
HashMap<String, Object> hm = new HashMap();
List<String> list = new ArrayList();
for (int i = 0; i < numbers.length; i++) {
list.add(numbers[i]);
hm.put("&mobile=", list);
}
System.out.println("HashMap: " + hm.get("&mobile="));
System.out.println("message: " + message);
//prints HashMap: [996****730, 97052***86, 984****956]
如何将其添加为逗号分隔值,如:
String mainUrl = "http://smshorizon.co.in/api/sendsms.php?";"&mobile= MOBILE_NUMBER1, MOBILE_NUMBER2, MOBILE_NUMBER3";
答案 0 :(得分:2)
使用Java 8,可以这样做:
String[] numbers = {"MOBILE_NUMBER1", "MOBILE_NUMBER2", "MOBILE_NUMBER3"};
System.out.println(Arrays.stream(numbers).collect(Collectors.joining(",")));
<强>输出:强>
MOBILE_NUMBER1,MOBILE_NUMBER2,MOBILE_NUMBER3
对于以前版本的Java,请使用StringBuilder
,如下所示:
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < numbers.length; i++) {
if (i > 0) {
buffer.append(',');
}
buffer.append(numbers[i]);
}
System.out.println(buffer);
<强>输出:强>
MOBILE_NUMBER1,MOBILE_NUMBER2,MOBILE_NUMBER3
答案 1 :(得分:2)
最简单的方法是使用StringBuilder并迭代你的数字,然后追加数字本身和逗号。然后你要删除最后一个字符(尾随逗号)并将你构建的字符串作为你的值。
示例强>
StringBuilder sb = new StringBuilder();
// assuming the "numbers" variable is a String array or collection
for (String number: numbers) {
sb.append(number).append(",");
}
// removing trailing ","
sb.deleteCharAt(sb.length() - 1)
hm.put("&mobile=", sb.toString());
答案 2 :(得分:1)
为什么不试试这个:
HashMap<String, Object> hm = new HashMap();
String mobileNumbers;
for (int i = 0; i < numbers.length; i++) {
mobileNumbers = mobileNumbers + "," + numbers[i];
}
mobileNumbers = mobileNumbers.subString(1); //To remove first comma.
hm.put("&mobile=", mobileNumbers);
System.out.println("HashMap: " + hm.get("&mobile="));
System.out.println("message: " + message);
//prints HashMap: 99****8730, 97******86, 98******56