0

I'm trying to rearrange my ArrayList by a specific string. so I'd like to rearrange my list by giving a priority to the type "truck" than the type "sedan" or the type "SUV". Technically, I could use reverseorder from their alphabetical order but I'd like to implement where a specific string itself has the priority. For example, if I have a list of cars in random order as following,

ArrayList<Car> cars = new ArrayList<Car>(Arrays.asList(
new Car("1", "truck"), 
new Car("2", "sedan"), 
new Car("3", "SUV"), 
new Car("4", "truck"), 
new Car("5", "truck"));

so that my ideal order should be 1,4,5,2,3. I appreciate any ideas!

  • See also the tutorial on method references: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html – markspace Jul 24 '21 at 22:22
  • 1
    Hmm, now I have to ask. Do you not know how to use comparators (which is what the duplicate link explains) or do you specifically not know how to get a comparator to sort in your desired order? – markspace Jul 24 '21 at 22:28

2 Answers2

0

You can sort based on the index in a List.

List<String> order = Arrays.asList("truck", "sedan", "SUV");
cars.sort(Comparator.comparingInt(c -> order.indexOf(c.getType()));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Just of the top of my head,l. First for the 'types' I would create an enum of all of your types that has the property 'priority' (an integer maybe). If this is a custom class you wrote/have access to edit I would implement the comparable interface on the car class after you change the class so the 'type' uses the enum instead of the string. As long as the enum matches the string given you can use the search method to match the string against the enum name( not sure if case sensitive), see here for a good example on how to implement the comparable interface https://www.javatpoint.com/Comparable-interface-in-collection-framework. Then implement compare to based on the enumeration priority value.

Zevrant
  • 115
  • 1
  • 9