简体   繁体   English

使用Java 8将一种类型的列表转换为另一种类型的数组

[英]Convert List of one type to Array of another type using Java 8

I need to convert List of string to Array of userdefinedType and for array I need to convert string to long. 我需要将字符串列表转换为userdefinedType的数组,对于数组,我需要将字符串转换为long。

I have achieved the same using below approach to achieve it 我已经使用以下方法实现了相同的目的

TeamsNumberIdentifier[] securityPolicyIdArray = securityPolicyIds.stream()
                .map(securityPolicy -> new TeamsNumberIdentifier(Long.valueOf(securityPolicy)))
                .collect(Collectors.toCollection(ArrayList::new))
                .toArray(new TeamsNumberIdentifier[securityPolicyIds.size()]);

Is there any better approach to convert this? 有没有更好的方法来转换它?

You don't need to create a temporary ArrayList. 您无需创建临时ArrayList。 Just use toArray() on the stream: 只需在流上使用toArray()即可:

TeamsNumberIdentifier[] securityPolicyIdArray = securityPolicyIds.stream()
            .map(securityPolicy -> new TeamsNumberIdentifier(Long.valueOf(securityPolicy)))
            .toArray(TeamsNumberIdentifier[]::new);

But in general, I would tend to avoid arrays in the first place, and use lists instead. 但总的来说,我倾向于避免首先使用数组,而是使用列表。

I would write it like this: 我会这样写:

securityPolicyIds.stream()
                 .map(Long::valueOf)
                 .map(TeamsNumberIdentifier::new)
                 .toArray(TeamsNumberIdentifier[]::new);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM