import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

/** Un índice de palabras: para cada palabra, el conjunto de líneas donde aparece. */
public final class WordIndex {

    private WordIndex() {
    }

    /** Las líneas se numeran desde 1. Palabras y números de línea salen ordenados. */
    public static Map<String, Set<Integer>> index(List<String> lines) {
        Map<String, Set<Integer>> index = new TreeMap<>();
        for (int i = 0; i < lines.size(); i++) {
            for (String word : lines.get(i).toLowerCase().split("[^\\p{L}]+")) {
                if (word.isEmpty()) {
                    continue;
                }
                Set<Integer> where = index.get(word);
                if (where == null) {                // primera vez: se crea su conjunto
                    where = new TreeSet<>();
                    index.put(word, where);
                }
                where.add(i + 1);
            }
        }
        return index;
    }
}
