简体   繁体   中英

Java TreeMap return key position

i Have this tree map:

Map teamNameAndLeague = new TreeMap();

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

How can i search for a key and return index of that key Example:

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

i have this:

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

That returns: 2

it returns the index for this key but for search on key value. How can i make something similar but instead search for key

TreeMap does not use an index; it's a tree, not a linear sequence. If you wish to impose an ordering, you may do so.

For this, you must supply a Comparator for the keys (the default string Comparator will do, if you wish), sort the list into an array, and then index the array, much as you've already posted with the values. Note, however, that this ignores the tree structure. See the example in http://java2novice.com/java-collections-and-util/treemap/basic-comparator/

Also, note the list of links at the bottom of the page: these will walk you through the basic TreeMap operations.

Another way is to use the "set" object from the keys, teamNameAndLeague.keySet; this, too ignores the tree structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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