java - Sort a map of objects with multiple fields using a comparator -
i have author
object name
, age
, , index
fields. authors stored in hashmap (the key index).
i able sort name , age.
this begins method want put in author class not understanding this:
public static linkedhashmap<string, author> sortname(map<string, author> unsortedmap){ collection<author> list = unsortedmap.values(); collections.sort(list, new comparator<author>() { public int compare(author a, author b) { return a.name.compareto(b.name); } }); }
it won't compile because of this: (from eclipse)
the method sort(list<t>, comparator<? super t>) in type collections not applicable arguments (collection<author>, new comparator<author>(){})
the collections class fields empty_list, empty_map, , empty_set. why can't sort method pass map comparator?
i thought
<t>
generic pass kind of object wanted.am correct if worked, collections.sort() sort
list
author's name? endlinkedlist<author>
turnlinkedhashmap<string, author>
, send on it's way?
thank in advance. i'm student. i've searched hours information guide me toward solution. i've read every question re: "collections sort multiple values comparator". nothing working.
i won't compile because collections.sort()
sorts lists
, not collections
.
if want sort values, it's east turn collection list passing collection constructor of list:
list<author> list = new arraylist<author>(unsortedmap.values()); collections.sort(list, new comparator<author>() { public int compare(author a, author b) { return a.name.compareto(b.name); } });
but won't job done. instead, need sort map
's entry
objects, put them map:
public static linkedhashmap<string, author> sortname(map<string, author> unsortedmap) { list<map.entry<string, author>> list = new arraylist<map.entry<string, author>>(unsortedmap.entryset()); collections.sort(list, new comparator<map.entry<string, author>>() { public int compare(map.entry<string, author> a, map.entry<string, author> b) { return a.getvalue().name.compareto(b.getvalue().name); } }); linkedhashmap<string, author> result = new linkedhashmap<string, author>(); (entry<string, author> entry : list) { result.put(entry.getkey(), entry.getvalue()); } return result; }
Comments
Post a Comment