2015-10-13 85 views
-1

我有这样的树状图:的Java TreeMap的返回键位置

Map teamNameAndLeague = new TreeMap(); 

teamNameAndLeague.put("team1", "name1"); 
teamNameAndLeague.put("team2", "name2"); 
teamNameAndLeague.put("team3", "name3"); 

我如何可以搜索键和返回键实例的指标:

search for key: "team1" in teamNameAndLeague, Returns index: 1 

我有这样的:

int indexWin = new ArrayList<String>(teamNameAndLeague.values()).indexOf("name2") + 1; 

That returns: 2 

它返回此密钥的索引,但是用于搜索密钥值。我怎么能做出类似的东西,而不是寻找钥匙

+0

它返回的索引基于关键...是不是搜索关键? – redFIVE

+0

你的索引是依赖于插入顺序还是根据TreeMap?我不认为在TreeMap中有任何索引 –

回答

0

为什么不做同样的事情,但用你的key得到value

new ArrayList<String>(teamNameAndLeague.values()).indexOf(teamNameAndLeague.get("team2")) + 1 

这将告诉你插入的顺序,但不会给你一个indexMap不使用index

0

TreeMap不使用索引;它是一棵树,而不是一个线性序列。如果你想强制订购,你可以这样做。为此,必须为键提供一个比较器(如果需要,默认字符串比较器将执行的操作),将列表排序到数组中,然后对数组进行索引,就像您已经发布的数组一样值。但请注意,这会忽略树结构。请参阅http://java2novice.com/java-collections-and-util/treemap/basic-comparator/中的示例

另请注意页面底部的链接列表:这些将引导您完成基本的TreeMap操作。

另一种方法是使用key的“set”对象,teamNameAndLeague.keySet;这也忽略了树结构。