I have a list of Country code values (which can be duplicated) and corresponding prices as shown in the Class Main, i want to find max/min in this way:
if Country Code = 0.1 , i should get it max price= 0.92 from 0.90, 0.91, 0.92. and so on for all other country codes
i.e. i want to Find max price for each distinct Country codes
i have done it successfully in the code shown below. But it is very slow and not good approach.
My Method: As the data in “Class Main” is related (country code, with price), i first sort the data by country code using Class “Telephone” with Comparator, and then i scan all the elements of the ” Telephone-ArrayList” and then i find the max value for each “Distinct” Country Code with comparison of ArrayList elements.
class Telephone implements Comparator<Telephone>{
private int countryCode;
private double price;
Telephone(){
}
Telephone( int c, double p){
countryCode= c;
price= p;
}
public int getCountryCode(){
return countryCode;
}
public double getPrice(){
return price;
}
// Overriding the compare method to sort
public int compare(Telephone d, Telephone d1){
return d.getCountryCode() - d1.getCountryCode();
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// Takes a list o Telephone objects
ArrayList <Telephone> list = new ArrayList<Telephone>();
ArrayList <Double> arr = new ArrayList<Double>();
list.add(new Telephone(1, 0.9));
list.add(new Telephone(268, 5.1 ));
list.add(new Telephone(46, 0.17 ));
list.add(new Telephone(46, 0.01));
list.add(new Telephone(4631, 0.15 ));
list.add(new Telephone(4620, 0.0 ));
list.add(new Telephone(468, 0.15 ));
list.add(new Telephone(46, 0.02));
list.add(new Telephone(4673, 0.9));
list.add(new Telephone(46732,1.1));
list.add(new Telephone(1, 0.91 ));
list.add(new Telephone(44, 0.4 ));
list.add(new Telephone(92, 0.4 ));
list.add(new Telephone(467, 0.2 ));
list.add(new Telephone(4, 0.0001 ));
list.add(new Telephone(1, 0.92 ));
list.add(new Telephone(44, 0.5 ));
list.add(new Telephone(467, 1.0 ));
list.add(new Telephone(48, 1.2 ));
list.add(new Telephone(4, 0.1));
Collections.sort(list, new Telephone());
for ( int i=0; i < list.size()-1; i++)
{
arr.clear();
while ( list.get(i).getCountryCode()== list.get(i+1).getCountryCode())
{
arr.add(list.get(i).getPrice()) ;
i=i+1;
}
arr.add(list.get(i).getPrice());
arr.trimToSize();
System.out.println( " Max value is " + Collections.max(arr).toString() + " for " +list.get(i).getCountryCode());
}
}
}
You could let
TelephoneimplementComparableand if the counrycodes are equal you could calculate your price into the comparison. If you sort your list then, you will have it sorted by contrycode first and then by price.You can then iterate over your Telephone colection and keep the contrycode for each interation. The last element of a countrycode you iterated over will be the one with the highest price. This way you can do the country code comparison and price comparison in one step.