Sorting using comparator and crieria from map using java 8 -
let's consider java class parent
20 attributes (attrib1, attrib2 .. attrib20) , corresponding getters , setters.
list<parent>
list contains n parent
objects.
now want sort list based on mutliple criteria. use comparator interface build sorting criteria.
the sorting arrtibutes stored map.
map< attributename, ascending/decending>
so want iterate through map , bulid comparator interface each key.
how can iterate through map , build comparator interface each key , connect these comparator interfaces.
i accept pure java 8 code solve problem.
unless use reflection, it's not possible achieve this. furthermore, if don't use linkedhashmap
or attributes' names not chained in lexicographical or other defined order ensure chain them in correct order, it'll not possible retrieve 1 want chain first.
to honest, using reflection seems more hack. think improve design.
what suggest create linkedhashmap<string, comparator<parent>> map = new hashmap<>();
(if don't need keys linkedhashset
might sufficient), there insert comparators in order want chain them.
then you're looking reduction. iterate through set of entries' value, , chain comparator reducing them:
comparator<parent> cmp = map.entryset() .stream() .map(map.entry::getvalue) .reduce(comparator::thencomparing) .get(); //check orelse, orelsethrow, etc.
if map
not linkedhashmap
keys can compared desired chain, can sort stream .sorted(map.entry.comparingbykey())
example.
you can either have map<string, simpleentry<comparator<parent>, boolean>>
if want store logic ascending/descending, you'd need add mapping operation:
... .map(map.entry::getvalue) .map(e -> e.getvalue() ? e.getkey().reversed() : e.getkey()) ...
so example of such map
be
map<string, simpleentry<comparator<parent>, boolean>> map = new hashmap<>(); map.put("id", new simpleentry<>(comparator.comparingint(parent::getid), true)); map.put("name", new simpleentry<>(comparator.comparing(parent::getname), false));
Comments
Post a Comment