java - How can we pass a variable field /method name in Comparator.comparing -


i have report {string name, date date, int score } class. want able sort list of reports member variable using new java 8 syntax

so java 8 provides new

list.sort(comparator.comparing(report -> report.name))  

to sort list on name.

lets instead of name want provide variable field name method eg. like

list.sort(comparator.comparing(report -> report.anyfield)) 

where anyfield can name or date or score. how achieve behavior.

one generic solution use java's reflection , casting:

    string sortby = "name";     list.sort(comparator.comparing(report -> {         try {             return (comparable) report.getclass().getdeclaredfield(sortby).get(report);         } catch (exception e) {             throw new runtimeexception("ooops", e);         }     }));     

if use additional library https://github.com/jooq/joor code becomes simpler:

    string sortby = "score";     list.sort(comparator.comparing(report -> reflect.on(report).field(sortby).get())); 

please aware solution works fields implement comparable , has runtime overhead.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -