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>(){})

  1. the collections class fields empty_list, empty_map, , empty_set. why can't sort method pass map comparator?

  2. i thought <t> generic pass kind of object wanted.

  3. am correct if worked, collections.sort() sort list author's name? end linkedlist<author> turn linkedhashmap<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

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -