Greetings, colleagues!

There is a ready and sorted TreeMap .

How to get a key-value pair from it based on the sequence number i ? Type:

 for (i = 0; i < map.size(); i++) 

    2 answers 2

    You can get a certain pair by the index index , for example, like this:

     TreeMap<Object, Object> foo = new TreeMap<Object, Object>(); Object key = foo.keySet().toArray(new Object[foo.size()])[index]; Object value = foo.get(key); 
    • one
      Thanks, it is! As reputation grows, I can thank you in an adult way;) - Batir Tashmetov
    • Why create an array each time, when you can get to the desired element with a simple iteration? - Sergey
     public static <K, V> Map.Entry<K, V> getEntryByIndex(Map<K, V> map, int index) { if (index < 0 || map.size() <= index) { throw new IndexOutOfBoundsException("индекс выходит за границы"); } Map.Entry<K, V> e = null; Iterator<Map.Entry<K, V>> it = map.entrySet().iterator(); while (0 <= index--) { e = it.next(); } return e; } 

    Application

     Map<String, String> m = new TreeMap<String, String>() {{ put("1", "1"); put("2", "2"); }}; Map.Entry<String, String> e = getEntryByIndex(m, 1); 

    And if you just need to get all the entry in a loop together with a sequence number, then this is completely elementary.

     int i = 0; for (Map.Entry e : m.entrySet()) { System.out.println("Порядковый номер: " + i); System.out.println("Ключ: " + e.getKey()); System.out.println("Значение: " + e.getValue()); i++; }