skywall
skywall

Reputation: 4005

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

Upvotes: 0

Views: 472

Answers (2)

ifloop
ifloop

Reputation: 8386

In Java 8 use Stream API for the most simple way:

Map<Long, MyClass> map = myClassList.stream().collect(Collectors.toMap(MyClass::getId, c -> c));

As you care for efficency, you should use HashMap instead of TreeMap. Specifying the implementation of Map looks like this:

Map<Long, MyClass> map = myClassList.stream()
        .collect(HashMap::new, (map, myClass) -> map.put(myClass.getId(), myClass), HashMap::putAll);

Upvotes: 1

Beri
Beri

Reputation: 11620

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.

Upvotes: 2

Related Questions