'How to sort based on dynamic list of column numbers using Comparator in Java

I have an ArrayList of Object[N_COLUMNS]. I need to sort this ArrayList, based on dynamic runtime conditions. At runtime I get a list of column numbers to sort by, say [3,2,4], and need to sort by column 3 first, for tied rows by column 2, and if still tied by column 4. The number of columns to sort by can vary. The Object[] arrays contains only classes implementing Comparable, and/or null values.

For a static case I know how to do this using the fluent API of Comparator, but I cannot figure out how to do it for a dynamically configured search criteria. The search needs to be null-safe and multi-keyed.

Any help would be greatly appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source