Search code examples
javalisttreemap

Java List<MyClass> to TreeMap<Long, MyClass>


is there any way, how to convert List<MyClass> to TreeMap<Long, MyClass> with reasonable performance? I have found method Maps.uniqueIndex() in Google Collections, but it return only Map.

List can be destroyed during process of conversion, I need just TreeMap. I use TreeMap because i need fast search and indexation with long.

Thanks in advance


Solution

  • There is no simpler method than iteration.

    Map<Long, MyClass> tree = new HashMap<Long, MyClass>();
    for (MyClass cl: classList){
       tree.put(cl.getId(), cl);
    }
    

    Just like Seelenvirtuose mentioned: If you want search performance: HashMap, if you want your elements to be sorted use TreeMap. In search performance goes to HashMap.