TopNWindowedMapGauge extends WindowedMapGauge<V> { protected Map<String, V> topN(Map<String, V> map) { Map<String,V> result = new HashMap<>(); Stream<Map.Entry<String,V>> st = map.entrySet().stream(); Comparator<Map.Entry<String,V>> comparator = Comparator.comparing( (Map.Entry<String, V> e) -> e.getValue()) .reversed(); st .sorted(comparator) .limit(n) .forEach(e -> result.put(e.getKey(), e.getValue())); return result; } TopNWindowedMapGauge(String name, long windowDurationMs, BiFunction<V, V, V> mergeFunc, int n);  TopNWindowedMapGauge(String name, long windowDurationMs, BiFunction<V, V, V> mergeFunc, int n, Clock clock); @Override Map<String, V> getSnapshot();  }
@Test public void testTopN() throws Exception { final long windowMs = 60000L; when(clock.currentTimeMillis()).thenReturn(0L); WindowedMapGauge<Long> gauge = new TopNWindowedMapGauge<>("wtf", windowMs, Long::max, 3, clock); gauge.update("key1", 1L); gauge.update("key2", 2L); gauge.update("key3", 3L); gauge.update("key4", 4L); gauge.update("key5", 5L); assertEquals(0, ((Map) gauge.getValue().get("data")).size()); when(clock.currentTimeMillis()).thenReturn(windowMs); assertEquals(0, ((Map) gauge.getValue().get("data")).size()); gauge.update("key1", 20L); assertEquals(3, ((Map<String, Long>) gauge.getValue().get("data")).size()); assertEquals( new HashSet<String>(Arrays.asList("key3", "key4", "key5")), ((Map<String, Long>) gauge.getValue().get("data")).keySet()); }