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:

  1. create map iterate through list
  2. get number first map
  3. put number key , name value in new map
  4. sort map key
  5. 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

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -