我必须使用ArrayList创建
HashMap<Integer,List<StoreItem>>
。我希望HashSet基于商店编号,就像我们在Ios中那样myArrayList.distinctUnionOfObjects.storeNumber
public static List<StoreItem> getStoreList(){
List<StoreItem> items = new ArrayList<>();
items.add(new StoreItem(503,"Brufeen",10));
items.add(new StoreItem(503,"hydriline",8));
items.add(new StoreItem(503,"Brufeen",10));
items.add(new StoreItem(503,"capsule",2));
items.add(new StoreItem(503,"Disprin",6));
items.add(new StoreItem(504,"Pixlar",9));
items.add(new StoreItem(504,"Luprin",17));
items.add(new StoreItem(504,"BOOM BOOM",14));
items.add(new StoreItem(504,"Glucophage",22));
items.add(new StoreItem(504,"Panadol",16));
items.add(new StoreItem(549,"Pixlar",9));
items.add(new StoreItem(549,"Luprin",17));
items.add(new StoreItem(549,"BOOM BOOM",14));
items.add(new StoreItem(549,"Glucophage",22));
items.add(new StoreItem(549,"Panadol",16));
return items;
}
public static HashMap<Integer,List<StoreItem>> getStoreHashMap(){
List<StoreItem> oldStores = StoreFactory.getStoreList();
Set<StoreItem> uniqueSet = new HashSet<StoreItem>(oldStores);
HashMap<Integer,List<StoreItem>> dictionaryOfStore = new HashMap<>();
for(StoreItem keyItem : uniqueSet )
{
List<StoreItem> storeInSection = new ArrayList<>();
for(StoreItem oldItem : oldStores)
{
if(keyItem.getStoreNumber() == oldItem.getStoreNumber()){
storeInSection.add(oldItem);
}
}
dictionaryOfStore.put(keyItem.getStoreNumber(),storeInSection);
}
return dictionaryOfStore;
}
uniqueSet返回15,因为它比较了整个StoreItem对象。我需要一个基于StoreItem.getStoreNumber()
创建HashSet的方法其中StoreItem
public class StoreItem {
private int storeNumber;
private String capsuleNames;
private int quantity;
public StoreItem(int storeNumber, String capsuleNames, int quantity) {
this.storeNumber = storeNumber;
this.capsuleNames = capsuleNames;
this.quantity = quantity;
}
}
还是有办法覆盖hashset Comparison。
而且我知道我可以用For循环中的check进行。
答案 0 :(得分:2)
我认为你不能用比较器实现这一目标。您可以像这样更改getStorehashMap()方法:
public static HashMap<Integer, List<StoreItem>> getStoreHashMap() {
List<StoreItem> oldStores = getStoreList();
HashMap<Integer, List<StoreItem>> dictionaryOfStore = new HashMap<Integer, List<StoreItem>>();
for (StoreItem keyItem : oldStores) {
if(!dictionaryOfStore.containsKey(keyItem.getStoreNumber())) {
dictionaryOfStore.put(keyItem.getStoreNumber(), new ArrayList<StoreItem>());
}
dictionaryOfStore.get(keyItem.getStoreNumber()).add(keyItem);
}
return dictionaryOfStore;
}