Spaces:
Running
Running
TurkuBasicOOPinJava
/
Week 3: Objects, files and exceptions
/21. Phone book 3: Listing numbers - Extract HASHMAP KEYS, then SORT
| q21 | |
| Write the method | |
| void listBook(HashMap<String,String> numbers | |
| which prints the users in the book and their numbers below them on the screen. | |
| The names should be printed in alphabetical order. | |
| An example of how to call the method: | |
| public static void main(String[] args){ | |
| HashMap<String,String> numbers = new HashMap<>(); | |
| numbers.put("Tina", "12345"); | |
| numbers.put("Keith", "54321"); | |
| numbers.put("Jack", "55555"); | |
| listBook(numbers); | |
| } | |
| Program outputs: | |
| Name: Jack, number: 55555 | |
| Name: Keith, number: 54321 | |
| Name: Tina, number: 12345 | |
| import java.util.Random; | |
| import java.util.Arrays; | |
| import java.util.HashMap; | |
| import java.util.Collections; | |
| import java.util.ArrayList; | |
| import java.util.Scanner; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| // <hide> | |
| HashMap<String, String> numbers = new HashMap<>(); | |
| numbers.put("Pete", "" + r.nextInt(1000000)); | |
| numbers.put("Lena", "" + r.nextInt(1000000)); | |
| numbers.put("Kim", "" + r.nextInt(1000000)); | |
| numbers.put("Laura", "" + r.nextInt(1000000)); | |
| numbers.put("Lisa", "" + r.nextInt(1000000)); | |
| numbers.put("Zorro", "" + r.nextInt(1000000)); | |
| numbers.put("Tarzan", "" + r.nextInt(1000000)); | |
| listBook(numbers); | |
| } | |
| //q21 | |
| public static void listBook(HashMap<String,String> numbers) { | |
| // https://stackoverflow.com/questions/9047090/how-to-sort-hashmap-keys | |
| // https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#keySet-- | |
| // sort the HashMap by key | |
| // String[] arrKeys = numbers.keySet().toArray(); //incorrect | |
| // new String[0] is an empty array of type String -> ie we want String[] array, even if empty array | |
| String[] arrKeys = numbers.keySet().toArray(new String[0]); //correct | |
| // sort inplace | |
| Arrays.sort(arrKeys); | |
| // correct option 2 - extract keySet as ArrayList, then use Collection to sort | |
| // Convert keySet to a List and sort it | |
| // ArrayList<String> arrKeys = new ArrayList<>(numbers.keySet()); | |
| // Collections.sort(arrKeys); | |
| // print the sorted HashMap | |
| for (String key : arrKeys) { | |
| System.out.println("Name: " + key + ", number: " + numbers.get(key)); | |
| } | |
| } | |
| } | |
| Name: Kim, number: 701584 | |
| Name: Laura, number: 417806 | |
| Name: Lena, number: 627033 | |
| Name: Lisa, number: 506742 | |
| Name: Pete, number: 292799 | |
| Name: Tarzan, number: 297377 | |
| Name: Zorro, number: 538240 | |