32U 32U - 9 months ago 52
Java Question

Java 8 Lambda Sort With Variable Method Reference

I have a statement:


where getD is an accessor in the class WCCTableRowData and searchResults is a list of WCCTableRowData. The WCCTableRowData class has accessors from getA through getZ. I need to be able to set the sort field on the fly from a passed in variable. Is there an elegant way to do this or will I need a series of if statements or similar?


One way is to add a method in WCCTableRowData that can be given a field name and returns the value of that field.

class WCCTableRowData {
    Comparable<?> getField(String name) { ... }

String name = "C";
searchResults.sort(Comparator.comparing(row -> row.getField(name)));

If you don't want to modify the class, then you could set up an external map.

Map<String, Function<WCCTableRowData, Comparable<?>>> getters = new HashMap<>();
getters.put("A", WCCTableRowData::getA);
getters.put("B", WCCTableRowData::getB);
getters.put("C", WCCTableRowData::getC);

String name = "C";