优化一下List<JSONObject> principalUsers = new ArrayList<>(); StringBuffer sb = new StringBuffer(); String principal = specialWorkSignature.getPrincipal(); List<String> principalUserList = Arrays.asList(principal.split(",")); principalUserList.forEach(c -> { sb.append(0).append(","); }); specialWorkSignature.setPrincipalFile(sb.deleteCharAt(sb.length() - 1).toString()); String recipient = specialWorkSignature.getRecipient(); List<String> recipientUserList = Arrays.asList(recipient.split(",")); StringBuffer sc = new StringBuffer(); recipientUserList.forEach(c -> { sc.append(0).append(","); }); specialWorkSignature.setRecipientFile(sc.deleteCharAt(sc.length() - 1).toString());
时间: 2024-03-20 11:44:47 浏览: 72
使用JSONObject解析json数据
可以使用Java 8引入的 `String.join()` 方法和 `Stream` API 来优化这段代码,如下所示:
```
List<String> principalUserList = Arrays.asList(specialWorkSignature.getPrincipal().split(","));
String principalFile = String.join(",", Collections.nCopies(principalUserList.size(), "0"));
specialWorkSignature.setPrincipalFile(principalFile);
List<String> recipientUserList = Arrays.asList(specialWorkSignature.getRecipient().split(","));
String recipientFile = String.join(",", Collections.nCopies(recipientUserList.size(), "0"));
specialWorkSignature.setRecipientFile(recipientFile);
```
这里,我们使用 `Collections.nCopies()` 方法创建一个包含指定元素数量的、重复指定元素的不可变列表。然后使用 `String.join()` 方法将这个列表中的所有元素用指定分隔符连接起来,生成一个新的字符串。这样可以避免使用循环对字符串进行操作,提高代码的简洁性和性能。
阅读全文