All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hubspot.mesos.CounterMap Maven / Gradle / Ivy

The newest version!
package com.hubspot.mesos;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;

public class CounterMap {

  private final Map map;

  public CounterMap() {
    this.map = new HashMap();
  }

  public CounterMap(int initialCapacity) {
    this.map = new HashMap(initialCapacity);
  }

  public Map toCountMap() {
    Map result = Maps.newHashMapWithExpectedSize(map.size());

    for (Entry entry : map.entrySet()) {
      result.put(entry.getKey(), entry.getValue().count);
    }

    return result;
  }

  public static final class Counter {
    private long count;

    private Counter() {
      count = 0;
    }

    public long getCount() {
      return count;
    }

    @Override
    public String toString() {
      return "Counter [count=" + count + "]";
    }
  }

  public void incr(K key, long amount) {
    Counter c = map.get(key);

    if (c == null) {
      c = new Counter();
      map.put(key, c);
    }

    c.count += amount;
  }

  public void incr(K key) {
    incr(key, 1);
  }

  public long getCount(K key) {
    Counter c = map.get(key);

    if (c == null) {
      return 0;
    }

    return c.count;
  }

  public Collection getKeys() {
    return map.keySet();
  }

  public void clear() {
    map.clear();
  }

  public List> asSortedEntryList() {
    List> entries = new ArrayList>(map.size());

    for (Entry entry : map.entrySet()) {
      entries.add(entry);
    }

    Collections.sort(entries, new Comparator>() {

      @Override
      public int compare(Entry o1, Entry o2) {
        return Longs.compare(o2.getValue().getCount(), o1.getValue().getCount());
      }

    });

    return entries;
  }

  @Override
  public String toString() {
    return "CounterMap [map=" + map + "]";
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy