Is there a ways to delete the last comma from this result?
ID = 1
Name = addsas
Absensi = 20
GajiPokok = 5000000
GajiTotal = 5400000
Tunjangan Makan= 400000
Email = [asdasd,asdasd,]
ID = 4
Name = asdas
Absensi = 20
GajiPokok = 5000000
GajiTotal = 5400000
Tunjangan Makan= 400000
Email = [asdasd,asdas,]
The result I hope is [asdasd,asdas]
without comma in the last
Here is my code. Is that because of the while loop that preventing the last comma to be deleted?
JSONArray email = (JSONArray) jsonObject.get("email");
@SuppressWarnings("unchecked")
Iterator<String> it = email.iterator();
System.out.print("Email = ");
System.out.print("[");
String a = "";
while (it.hasNext()) {
a = it.next() + ",";
System.out.print(a.replaceAll(", $", ""));
}
System.out.print("]");
System.out.println("\n");
}
If you develop in Java 8+ env, you can use stream api to solve such issue:
String result = email.stream().collect(Collectors.joining(","))
Collectors.joining(",")
will add comma between items of the list and will omit comma for the very last element.
emails = List.of("a","b");
result = "a,b";
emails = List.of("a");
result = "a";
it is possible to future enrich the pipeline to add [
and ]
List.of("a").stream().collect(Collectors.joining(",","[","]"))
// produces "[a]"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.