package org.academiadecodigo.enuminatti.wordhistogram;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class WordHistogram implements Iterable<String> {

    private Map<String, Integer> histogram;

    public WordHistogram() {
        histogram = new LinkedHashMap<>();
    }

    public void putAll(String[] words) {
        for (String word : words) {
            // putIfAbsent doesn't change anything if the key exists
            Integer ret = histogram.putIfAbsent(word, 1);
            if (ret != null) {
                // put replaces the value
                histogram.put(word, ++ret);
            }
        }
    }

    public int countUses(String word) {
        return histogram.get(word);
    }

    @Override
    public Iterator<String> iterator() {
        return histogram.keySet().iterator();
    }
}
