For starters, let's parse the lines from your file into Car objects instead of putting them in one big String:
public static void main(String[]args) throws Exception
{
FileReader file = new FileReader("C:/Users/Aaron/Documents/java/car_file.txt");
BufferedReader reader = new BufferedReader(file);
List<Car> cars = new ArrayList<Car>();
String line = reader.readLine();
while (line!= null)
{
cars.add(new Car(line));
line = reader.readLine();
}
}
public class Car {
private String type;
private String brand;
private String model;
private int price;
public Car(String spec) {
String[] parts = spec.split(",");
if (parts == null || parts.length != 4) {
throw new IllegalArgumentException("Bad car specification: " + spec);
}
int i = 0;
type = parts[i++];
brand = parts[i++];
model = parts[i++];
price = Integer.parseInt(parts[i++]);
}
public int getPrice() {
return price;
}
// other getters and setters could go here
public String toString() {
return String.format("Car type=%s, brand=%s, model=%s, price=%s", type, brand, model, price);
}
}
Now we need to sort them. One way to do this is implement a Comparator. One of the other answers describes another way to do this by letting the Car class implement Comparable. The reason I didn't choose that solution is that it only allows one sorting order for cars. If you later want to be able to sort by something else too then that would not be possible using Comparable. So using a separate Comparator is more loosely coupled and thus offers more flexibility.
If you look at the JavaDoc of Comparator's compare method (see link above) it says:
Compares its two arguments for order. Returns a negative integer, zero, or a positive
integer as the first argument is less than, equal to, or greater than the second.
So we must return a negative integer if the first argument is less than the second:
public class CarPriceComparator implements Comparator<Car> {
@Override
public int compare(Car o1, Car o2) {
return o1.getPrice() - o2.getPrice();
}
}
Now you can sort your list of Cars, for example by calling Collections.sort
Collections.sort(cars, new CarPriceComparator());
And print the result:
for(Car car : cars) {
System.out.println(car);
}
Note: I implemented toString in Car, otherwise the above code would only print the object references of the cars.