如何在Java中将一个列表转换为另一个列表?

时间:2019-09-06 04:52:07

标签: java list caching arraylist java-8

我已将Cache声明为Map:

private Cache<String,Object> operatingParametersCache;

我正在从服务类获取数据,并将其放入Cache:

List<OperatingParametersDTO> objList=this.operatingParamService.getOperatingParamDTO();

          operatingParametersCache = cacheManager
                .createCache("cacheOfOperatingService", CacheConfigurationBuilder
                        .newCacheConfigurationBuilder(
                                String.class,Object.class,
                                ResourcePoolsBuilder.heap(100000)).withExpiry(Expirations.timeToLiveExpiration(Duration.of(60000,
                                TimeUnit.SECONDS))));

        operatingParametersCache.put("CACHE_OPERATING_PARAMETER",objList);

我尝试使用以下方法从缓存中获取值:

 List<Object> operatingvalues = new ArrayList<>();
        operatingParametersCache.forEach(entry -> operatingvalues.add(entry.getValue()));
        System.out.println(operatingvalues);

我想将此List<Object>转换为List<OperatingParametersDTO>,所以我尝试使用:

List<OperatingParametersDTO> listA = new ArrayList<OperatingParametersDTO>(operatingvalues);

但是我得到了:无法解析构造函数'ArrayList(java.util.List)'

2 个答案:

答案 0 :(得分:3)

最简单的方法是声明具有正确类型的列表:

List<OperatingParametersDTO> operatingvalues = new ArrayList<>();

然后投射:

operatingParametersCache.forEach(entry -> operatingvalues.addAll(((List) entry.getValue()).stream().map(el -> (OperatingParametersDTO) el).collect(Collectors.toList())));

您还可以投射每个元素:

List<OperatingParametersDTO> listA = operatingvalues.stream()
    .map(el -> (OperatingParametersDTO) el)
    .collect(Collectors.toList());

您不能将一种类型的集合转换为另一种类型的集合,更多详细信息here

答案 1 :(得分:0)

您可以在此处使用FlatMap

// Dummy Values (I have created 2 fields id and name)
List<OperatingParametersDTO> objList = new ArrayList<>();
objList.add(new OperatingParametersDTO(1, "ABC"));
objList.add(new OperatingParametersDTO(2, "DEF"));
objList.add(new OperatingParametersDTO(3, "GHI"));

// Adding List to Map
Map<String, Object> operatingParametersCache = new HashMap<>();
operatingParametersCache.put("CACHE_OPERATING_PARAMETER", objList);

// Converting List<Object> to List<OperatingParametersDTO> and printing
List<OperatingParametersDTO> listA  = operatingParametersCache.values().stream().map(e -> (List<OperatingParametersDTO>) e).flatMap(List::stream).collect(Collectors.toList());
System.out.println(listA);
  

输出:

[OperatingParametersDTO{id=1, name='ABC'}, OperatingParametersDTO{id=2, name='DEF'}, OperatingParametersDTO{id=3, name='GHI'}]