java - Sort list based on priority from a map -
i have simple map , need create list sorted based on number in ascending order given list:
map auto = new hashmap(); auto.put("merc", 3); auto.put("citroen", 5); auto.put("opel", 10); auto.put("bmw", 20); list<string> given = new arraylist<>(); given.add("opel"); given.add("bmw"); given.add("citroen"); so given list needs sorted in order: citroen, opel, bmw. thinking of:
- create map iterate through list
- get number first map
- put number key , name value in new map
- sort map key
- iterate threw new map add values list
this seems terrible :/, suggestions , perhaps better data structures use?
using java 8 can do.
map<string, integer> auto = new hashmap<>(); auto.put("merc", 3); auto.put("citroen", 5); auto.put("opel", 10); auto.put("bmw", 20); list<string> given = new arraylist<>(); given.add("opel"); given.add("bmw"); given.add("citroen"); // sort selected elements. given.sort(comparator.comparing(auto::get)); // sort elements. list<string> names = auto.entryset().stream() .sorted(comparator.comparing(map.entry::getvalue)) .map(map.entry::getkey) .collect(collectors.tolist()); breaking down
list<string> names = // give set of entries stream. auto.entryset().stream() // sort these entries, using field returned getvalue() .sorted(comparator.comparing(map.entry::getvalue)) // sorted, turn each entry getkey() .map(map.entry::getkey) // have stream of keys, turn list<string> .collect(collectors.tolist());
Comments
Post a Comment