简体   繁体   English

如何将单词存储为 TreeMap 中的键?

[英]How Do I Store Words as Keys in a TreeMap?

Using a TreeMap, how would I use a comparator to map keys which are words to corresponding linked lists.使用 TreeMap,我将如何使用 map 键的比较器,这些键是对应链接列表的单词。

TreeMap<String, LinkedList<String>()> () words = new TreeMap(<Comparator> );

Is there a specific comparator I can use or do I have to implement a way for it to alphabetically sort the words I add to the TreeMap?是否有我可以使用的特定比较器,或者我是否必须实现一种方法来按字母顺序对我添加到 TreeMap 的单词进行排序?

No need for a Comparator .不需要Comparator

As a NavigableMap , a TreeMap promises to keep its keys sorted.作为NavigableMapTreeMap承诺保持其键排序。

And String class, the class of your map's keys, already implements Comparable .并且地图键的 class String class 已经实现了Comparable So string objects know how to be sorted.所以字符串对象知道如何排序。 With keys that are Comparable , you need not specify a Comparator .使用Comparable的键,您无需指定Comparator

Also, generally best to declare your collection in a more general way using interfaces or superclasses.此外,通常最好使用接口或超类以更通用的方式声明您的集合。 This leaves room for you to change your concrete classes later without breaking other code.这为您在不破坏其他代码的情况下稍后更改具体类留下了空间。 So NavigableMap< String, List< String > > map rather than TreeMap< String, LinkedList< String > > map .所以NavigableMap< String, List< String > > map而不是TreeMap< String, LinkedList< String > > map

For example, in code below we are free to use List.of to produce a List of some unknown concrete class rather than being limited to only LinkedList as seen in your code.例如,在下面的代码中,我们可以自由地使用List.of来生成一些未知的具体 class 的List ,而不是仅限于在您的代码中看到的LinkedList

NavigableMap< String , List< String > > map = new TreeMap<>() ;

Example usage.示例用法。

map.put( "animals" , List.of( "dog" , "cat" , "bird" ) ) ;
map.put( "people" , List.of( "Alice" , "Bob" , "Carol" ) ) ;
map.put( "cars" , List.of( "Honda" , "Mazda" ) ) ;

See this code run live at IdeOne.com .请参阅在 IdeOne.com 上实时运行的代码

map.toString() ➡ {animals=[dog, cat, bird], cars=[Honda, Mazda], people=[Alice, Bob, Carol]} map.toString() ➡ {动物=[狗,猫,鸟],汽车=[本田,马自达],人=[爱丽丝,鲍勃,卡罗尔]}

Note how the "cars" entry has been sorted from 3rd-added to the 2nd position, between "animals" and "people" alphabetically.请注意"cars"条目是如何从第 3 个添加到第 2 个 position 排序的,在“动物”和“人”之间按字母顺序排列。

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

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