使用Java 8将一种类型的List转换为另一种类型的Array

时间:2016-12-14 18:32:14

标签: java java-8 java-stream

我需要将字符串List转换为userdefinedType数组,对于数组我需要将字符串转换为long。

我使用以下方法实现了相同的目标

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

有没有更好的方法来转换它?

2 个答案:

答案 0 :(得分:7)

您不需要创建临时ArrayList。只需在流上使用toArray():

package com.igorgorbunov3333.core.entities.service.impl;

import com.igorgorbunov3333.core.entities.domain.Case;
import com.igorgorbunov3333.core.entities.enums.CaseStatus;
import com.igorgorbunov3333.core.entities.service.api.CaseService;
import com.igorgorbunov3333.core.util.DateUtil;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.*;

/**
 * Created by Игорь on 27.07.2016.
 */

@Repository
@Service("CaseService")
public class CaseServiceImpl implements CaseService {

@PersistenceContext
private EntityManager entityManager;

@Transactional
public Case create(Case lawsuit) {
    entityManager.persist(lawsuit);
    return lawsuit;
}
}

但总的来说,我倾向于首先避免使用数组,而是使用列表。

答案 1 :(得分:1)

我会这样写:

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