I have a bunch of Shops:
public class Shop {
private final String shopName;
private boolean shopProperty1;
private boolean shopProperty2;
}
Now sometimes I need to retrieve a Shop by its shopName and sometimes I need to perform an operation to all existing Shops.
With ArrayList
List<Shop> shops = new ArrayList<>();
Shop shop1 = new Shop("Megastore", false, true);
Shop shop2 = new Shop("PC-shop", true, true);
Shop shop3 = new Shop("Jim's junkyard", false, false);
shops.add(shop1);
shops.add(shop2);
shops.add(shop3);
Iterating:
for (Shop shop : shops) {
doOperation(shop);
}
Retrieving Megastore by shopName:
Shop retrieved;
for (Shop shop : shops) {
if ("Megastore".equals(shop.getShopName())) {
retrieved = shop;
break;
}
}
My concerns for using this approach:
Retrieving by name seems rather slow with ArrayList and HashMap would be much better there.
With HashMap
Map<String, Shop> shops = new HashMap<>();
Shop shop1 = new Shop("Megastore", false, true);
Shop shop2 = new Shop("PC-shop", true, true);
Shop shop3 = new Shop("Jim's junkyard", false, false);
shops.put(shop1.getShopName(), shop1);
shops.put(shop2.getShopName(), shop2);
shops.put(shop3.getShopName(), shop3);
Iterating:
for (Shop shop : shops.values()) {
doOperation(shop);
}
Retrieving Megastore by shopName:
Shop retrieved = shops.get("Megastore");
My concerns for using this approach:
It seems redundant to have shopName as key when it is already a field of the Shop. Also I don't know how well HashMap has been designed to be iterated through.
So the question is: Which approach is better design practice or are there even better ways? How do programmers usually deal with this kind of situation?
Not a duplicate of When to use HashMap over LinkedList or ArrayList and vice-versa because this explains the potential problems with the approaches. Could be better in codereview though.