如何在Java中将一组更改为不同类型的列表?

时间:2018-12-20 11:42:30

标签: java list set

现在如何将set的值存储在列表中。这里的集合和列表具有不同的类型(ProductAttribute和PersistableProductAttribute)。

for(ProductRelationship productrelationship:productRelationshipList)
{
    Product product=productrelationship.getRelatedProduct();
    PersistableProduct ppTem=new PersistableProduct();

    Set<ProductAttribute> aSet = product.getAttributes();
    List<PersistableProductAttribute> aList = new ArrayList<PersistableProductAttribute>();
// I need to store here in a list.
}

1 个答案:

答案 0 :(得分:0)

这只是一个简单的例子,我自己尝试了几次后就得到了。首先,我需要为PersistableProductAttribute创建一个集合,我必须使用循环获取它的属性,然后将其复制到列表中。现在它可以正常工作,因为set和list是同一类型。因此,我们可以使用Java中的add()方法将集合复制到列表中。

 Set<PersistableProductAttribute> ppaSet = new 
 PersistableProductAttribute<>();
 for(ProductAttribute x:aSet)
 {
  // Get all the attributes here using get() 
  //and set() methods
  // Copy the set to list as follows,
    aList.add(ppaSet);
  }