我正在寻找一种简洁的方法来重写一段 Java 代码,以便它使用流以空安全方式将数组转换为列表。这是原始代码:
public MailObject toMailObject(final String[] ccAddresses) {
final MailObject mailObject = new MailObject();
// line of code to be altered
mailObject.setCcAddresses(ccAddresses == null
? Collections.emptyList() : Arrays.asList(ccAddresses));
// other necessary code
return mailObject;
}
我想过这样做:
// psuedocode that obviously doesn't compile
Optional.ofNullable(ccAddresses).SOMETHING.orElse(Collections.emptyList());
其中 SOMETHING 应该是:
Arrays.stream(ints).collect(Collectors.toList());
但我似乎无法完全正确地理解语法。
这question很有帮助,但没有完全解决我的问题。谁能指出我正确的方向?我觉得我很接近...
非常感谢您的宝贵时间。
最佳答案
您可能会使用 map
:
List<String> ccAddrs = Optional.ofNullable(ccAddress)
.map(Arrays::asList)
.orElse(Collections.emptyList())
关于java - 使用流进行从数组到列表的空安全转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55272522/