fork download
  1. /* package whatever; // don't place package name! */
  2. import java.util.*;
  3. import java.util.stream.*;
  4. import java.util.concurrent.atomic.AtomicInteger;
  5.  
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. public class Main
  9. {
  10. static Map<String, Integer> rooms = Map.of(
  11. "Gower", 281,
  12. "Usk", 291,
  13. "Wye", 283,
  14. "Bala", 282,
  15. "Pen y Fan", 292,
  16. "Llangorse", 290,
  17. "Snowdon", 288,
  18. "Taff", 296,
  19. "Cadair Idris", 292
  20. );
  21.  
  22. public static String[] getTopRoomsBooked(Map<String, Integer> rooms, int n) {
  23.  
  24. // just for the row id in inner print
  25. AtomicInteger id = new AtomicInteger(1);
  26.  
  27. Comparator<Map.Entry<String, Integer>> byTime = Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder());
  28. Comparator<Map.Entry<String, Integer>> byName = Comparator.comparing(Map.Entry::getKey);
  29.  
  30. return rooms.entrySet().stream()
  31. .sorted(byTime.thenComparing(byName))
  32. .limit(n)
  33. // inner print
  34. .peek(e -> System.out.printf("%d: %s %d%n", id.getAndIncrement(), e.getKey(), e.getValue()))
  35. .map(Map.Entry::getKey)
  36. .collect(Collectors.toList())
  37. .toArray(String[]::new);
  38. }
  39.  
  40.  
  41. public static void main (String[] args) throws java.lang.Exception
  42. {
  43. int[] arr = {1, 3, 5};
  44. Arrays.stream(arr)
  45. .forEach(a -> System.out.println("Top " + a + ":\n"
  46. + Arrays.toString(Main.getTopRoomsBooked(rooms, a))
  47. + "\n======\n"
  48. ));
  49. }
  50. }
Success #stdin #stdout 0.2s 38556KB
stdin
Standard input is empty
stdout
1: Taff 296
Top 1:
[Taff]
======

1: Taff 296
2: Cadair Idris 292
3: Pen y Fan 292
Top 3:
[Taff, Cadair Idris, Pen y Fan]
======

1: Taff 296
2: Cadair Idris 292
3: Pen y Fan 292
4: Usk 291
5: Llangorse 290
Top 5:
[Taff, Cadair Idris, Pen y Fan, Usk, Llangorse]
======