Skip to content
Advertisement

Sort the list of cars and display them sort by make using Java?

I have a question that sorts data from a car report of txt file.

The question is: How do I listed cars sorted by their MAKE (Ford, Chevy ..etc). They only need the MAKE to be sorted so they can be all FORD cars under each other, then Chevy, DODGE .. so on and so forth like this:

Cars sorted by their make

And this is what I have so far:

Car make are NOT sorted

Here’s my source code:

JavaScript
JavaScript

Here’s text file report:

JavaScript

Advertisement

Answer

it’s pretty straightforward :

  1. read all element and put them in a list:

    JavaScript
  2. sort the elements (I’m using streams, but probably Collections.sort might be less memory expensive since is in-place, e.g. Comparator.comparing(CustomerSale::getMake), thanks @Thomas):

    JavaScript
  3. and only at the end, print the output:

    JavaScript
Advertisement