[英]Convert List of one type to Array of another type using Java 8
我需要將字符串列表轉換為userdefinedType的數組,對於數組,我需要將字符串轉換為long。
我已經使用以下方法實現了相同的目的
TeamsNumberIdentifier[] securityPolicyIdArray = securityPolicyIds.stream()
.map(securityPolicy -> new TeamsNumberIdentifier(Long.valueOf(securityPolicy)))
.collect(Collectors.toCollection(ArrayList::new))
.toArray(new TeamsNumberIdentifier[securityPolicyIds.size()]);
有沒有更好的方法來轉換它?
您無需創建臨時ArrayList。 只需在流上使用toArray()即可:
TeamsNumberIdentifier[] securityPolicyIdArray = securityPolicyIds.stream()
.map(securityPolicy -> new TeamsNumberIdentifier(Long.valueOf(securityPolicy)))
.toArray(TeamsNumberIdentifier[]::new);
但總的來說,我傾向於避免首先使用數組,而是使用列表。
我會這樣寫:
securityPolicyIds.stream()
.map(Long::valueOf)
.map(TeamsNumberIdentifier::new)
.toArray(TeamsNumberIdentifier[]::new);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.