My application needs to read a file, which includes a list of cars from different factories, and calculate the prices (by this I mean mean add up their prices).
I suppose my solution is efficient. Is there any better approach to it?
String factories = "Benz,10000,BMW,3000,Benz,5,Toyota,500,BMW,50000,RR,100000,BMW,100000,Jaguar,100000,Benz,4,Next,100,Benz,3,Benz,2,Benz,1,Toyota,100000,Polo,10,Gall,1000";
String[] fac = factories.split(",");
List<Company> trn = new ArrayList();
for(int i=0;i<fac.length-1;i=i+2){
trn.add(new Company(fac[i],fac[i+1]));
}
Map<String, BigDecimal> map = new HashMap();
BigDecimal counter = new BigDecimal("0");
BigDecimal target = new BigDecimal("10000");
for (Company c : trn) {
String name = c.getName();
if (!map.containsKey(name)) {
counter = new BigDecimal("0");
for (Company com : trn) {
if (com.getName().equalsIgnoreCase(name)) {
counter = counter.add(com.getPrice());
if ((counter.compareTo(target)) == 1) {
map.put(name, counter);
}
}
}
}
}
Set<String> set = map.keySet();
System.err.println(">>" + set.toString());
Output
[RR, Toyota, BMW, Jaguar, Benz]