-1

I'm suffering to sort an object list by two attributes.

My Object Car has 3 attributes. name, type, price.

I need to order by type and price (lowest to highest).

The type is populated with Strings (EDMR, CMMD, JGAD, MDMR, etc) and needs to be ordered based in the first letter. The order needs to be M first than E than C than any other letter.

I need to get something like that:

Peugeot 107     - MCMR - 22.50
Nissan Micra    - MCMR - 25.50
Peugeot 107     - MCMR - 30.05
Opel Corsa      - EDMN - 29.50
Opel Corsa      - EDMN - 31.50
Volkswagen Golf - CDMR - 48.00
Mercedes A Class- ICAV - 80.00
Mercedes        - TVBN - 100.00

Could someone help me, please. I really don't now how to manage it.

Thank you so much for your time guys.

  • Gosh, there are [so many similar questions easily available](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+java+sort+multiple+fields). Please search first when asking a question that has likely been asked (here -- many many times) before. – Hovercraft Full Of Eels Jan 18 '17 at 01:08
  • In short, you should have your `Car` class implement the `Comparable` interface. Override the `compareTo` method and handle your comparison logic there. When you sort your list, it will use the `compareTo` method that you have defined. – Matt Jan 18 '17 at 01:09
  • Or use a Comparator, but again, these options are all well described in the similar questions. As for your compare or compareTo method specifics, that **you** should try to work out first. My guess is that you'll surprise yourself with what you can do. – Hovercraft Full Of Eels Jan 18 '17 at 01:10
  • I saw similar topics about sorting by more than one attribute but no one makes a sorting like I need. I really don't know how to sort like this: M first than E than C than any other letter. – Rafael Matos Jan 18 '17 at 01:22
  • Ya still must try something yourself first. Seriously. What do you have to lose in the attempt? – Hovercraft Full Of Eels Jan 18 '17 at 01:23
  • It's now 1:25am here, so I've tried by myself around 4 hours without success. I never did something like that before. Order a list it's easy, but using this letters criteria it's more complicated for me. – Rafael Matos Jan 18 '17 at 01:28
  • Your time constraints have no bearing on the question. This is obviously homework, and the rules of this site are clear: you should post your attempt. – Hovercraft Full Of Eels Jan 18 '17 at 01:28
  • It's for my job. I didn't know I had to post my attempt. I can post it. It's fair enough. Makes everyone try something before ask. I new here. I believe I will improve. – Rafael Matos Jan 18 '17 at 01:32

1 Answers1

-1

You may try to override the compareTo method in the Car class, then use sort method in Collections to sort the Car object.

Tim
  • 123
  • 1
  • 2
  • 11