java list 转 treemap
时间: 2023-09-05 10:12:56 浏览: 101
可以使用`Collections.sort()`方法将列表排序,然后通过循环将列表中的元素添加到`TreeMap`中。假设列表中的元素是`String`类型:
```java
import java.util.*;
public class ListToTreeMap {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("orange");
// sort the list
Collections.sort(list);
// create a TreeMap and add elements from the list
TreeMap<String, Integer> treeMap = new TreeMap<>();
for (String s : list) {
treeMap.put(s, s.length());
}
// print the TreeMap
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
```
输出结果为:
```
apple -> 5
banana -> 6
cherry -> 6
orange -> 6
```
阅读全文