【发布时间】:2015-12-19 19:30:35
【问题描述】:
我有不同类型的Sets,如下所示:
Set<String> imgs = new LinkedHashSet<String>(this.getImages());
Set<String> proNames = new LinkedHashSet<String>(this.getProductNames());
Set<Integer> proQty = new LinkedHashSet<Integer>(this.getQty());
Set<Double> proPrice = new LinkedHashSet<Double>(this.getPrices());
我需要将上述集合中的所有数据插入到一个用户定义的类型为ArrayList 中,如下所示:
List<MyProduct> pList = new ArrayList<MyProduct>();
for (Iterator<Double> iterator = proPrice.iterator(); iterator.hasNext();) {
Double next = iterator.next();
pList.add(new MyProduct(?, ?, ?, next));
}
考虑所有集合的大小都相同。(所有 4 个集合包含相同数量的数据)
MyProduct类:
public class MyProduct {
private String image;
private String proName;
private int qty;
private double price;
public MyProduct(String image, String proName, int qty, double price) {
this.image = image;
this.proName = proName;
this.qty = qty;
this.price = price;
}
//getters and setters
...
提前致谢。
更新:
假设我有 4 个 ArrayLists 而不是 Sets :
public ArrayList<String> proNames = new ArrayList();
public ArrayList<Double> proPrice = new ArrayList();
public ArrayList<Integer> proQty = new ArrayList();
public ArrayList<String> imgs = new ArrayList<String>();
但在这些列表中可能包含重复项。这意味着 proNames 有两种产品 Apple 和 Banana。但在 proPrice 我们有两种产品的价格 Apple 和 Banana 但有重复项。
(例如:假设 Apple--> $1 和 Banana--> $2。在
proPrice-->[1,2,2]香蕉的两倍价格。)。
那么在这种情况下,我怎样才能将这些数据放在我的List<MyProduct> 中??
【问题讨论】:
-
一开始为什么要把数据放到集合中呢?您不能通过集合按索引访问元素,因此不可能使用常规循环。您可能想要使用列表,除非您有理由尝试防止重复。然后,您可以使用索引循环访问列表中的每个元素。
-
是的。我有一些重复的元素。这就是为什么使用集合而不是列表的原因。
-
集合是无序的,所以如果你的四个集合应该是并行的,你需要使用列表或有序集合(例如
LinkedHashSet) -
所有的副本都一样吗?这似乎是一个可怕的想法。列表确实是这里的方法,然后在将它们组合到 MyProducts 后处理任何重复的解决方案。
-
@LouisWasserman 在将它们合并到
myProducts之前,我必须删除重复项。