简体   繁体   English

按长度存储和排序单词的最有效方法?

[英]Most efficient way to store and sort words by length?

Since many words might have the same length, an insertion operation to a certain database can be costly. 由于许多单词的长度可能相同,因此对某个数据库的插入操作可能会非常昂贵。

I saw the following suggestions for storing and sorting words by length. 我看到了以下有关按长度存储和排序单词的建议。 Which is the most efficient? 哪个最有效?

  1. Key: length of word, Value: Set of all words with that length. 键:单词长度,值:所有具有该长度的单词的集合。 Using HashMap: Sorting all words in a file by length, in one read. 使用HashMap: 在一次读取中按长度对文件中的所有单词进行排序。 (Java) (Java)

  2. Using Guava's MultiMap: https://stackoverflow.com/a/4244798/2653179 使用番石榴的MultiMap: https ://stackoverflow.com/a/4244798/2653179

  3. TreeMap? 树图? Or storing the words in an ArrayList, writing compare function, then using Collections.sort: Java: Sort a list of words by length, then by alphabetical order 或将单词存储在ArrayList中,编写比较函数,然后使用Collections.sort: Java:按长度,然后按字母顺序对单词列表进行排序

Or other suggestions? 还是其他建议?

Most efficient way to store and sort words by length? 按长度存储和排序单词的最有效方法?

Map<Integer, List<String>> - map where the key is the word length and the value is a list with words Map<Integer, List<String>> -映射,其中键是单词长度,值是包含单词的列表

With using Guava you could create a multimap with keys sorted by a length: 使用番石榴,您可以创建一个按长度排序的键的多图:

TreeMultimap<Integer, String> map = TreeMultimap.create();

//as Java's map 
NavigableMap<Integer, Collection<String>> asMap = map.asMap();

Adding items: 添加项目:

for (String word : new String[]{"cd", "efg", "k", "a", "b", "ab"}) {
    map.put(word.length(), word);
}

System.out.println("words: " + map);

Prints: 印刷品:

words: {1=[a, b, k], 2=[ab, cd], 3=[efg]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM