Skip to content
Advertisement

Sort collection according to user custom input by single or multiple attributes

I have collection of Item object and the class Item is as follows ->

JavaScript

Now, I want to sort according to the user input. User can sort it according to his choice like brand, price or publishedDate and even with the multiple parameters. Like brand and price or price and publishedDate.

I have seen Comparator to sort by multiple parameters but that also limited and with predefined parameters. So basically user can sort by any input and sorting mechanism can handle that without changing any code.

I get some hints to use strategic design pattern but not able to implement here to resolve it.

Advertisement

Answer

You could use a static Map for a Comparator for each field and build a combined Comparator out of that: You’d still have to make the comparators null-safe and check the field names…

JavaScript

EDIT

Version using comparing / thencomparing

The map could be omitted when using reflection to get the getters…

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement