Java集合——TreeMap,Collections工具类
TreeMap
核心和HashMap一样也是红黑树
实现了SortedMap接口(是Map的子接口),可以对key自动排序
TreeMap和TreeSet的关系
从TreeSet的源码中我们可以看到其实TreeSet内部就是TreeMap
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
public TreeSet() {
this(new TreeMap<>());
}
public interface NavigableMap<K,V> extends SortedMap<K,V> {
实例
由于其实现了sortedMap所以我们在进行实现的时候需要和TreeSet一样,实现Comparable接口或使用匿名内部类实现Comparator
下面的代码我使用了lambda表达式写Comparator如果看不懂可以去看我这篇文章:Java8新特性
package map.entity;
import java.util.Comparator;
import java.util.TreeMap;
public class demo3 {
public static void main(String[] args) {
TreeMap<Person, String> map = new TreeMap<>((o1, o2) -> {
int nameCom = o1.getName().compareTo(o2.getName());
return nameCom;
});
map.put(new Person(54, "zhangsan"), "1");
map.put(new Person(58, "andy"), "10");
map.put(new Person(34, "lisi"), "100");
map.forEach((x, y) -> {
System.out.println(x + "|" + y);
});
}
}
结果
Collections工具类
作为集合的工具类,定义了除了存取以外的集合的常用方法
常用方法
- reverse(list)
对集合进行翻转
- sort(list)
对集合进行排序
- binarySearch(list, param)
对集合中的元素进行获取索引号,param指元素
- shuffle(list)
将集合打乱
代码实例
package collectionUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Demo1 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("abs");
list.add("msadhk");
list.add("newword");
list.add("aaa");
list.add("xyz");
list.forEach(System.out::println);
Collections.reverse(list);
System.out.println("============");
list.forEach(System.out::println);
System.out.println("============");
Collections.sort(list);
list.forEach(System.out::println);
System.out.println("===========");
//得到abs的索引号
int abs = Collections.binarySearch(list, "abs");
System.out.println(abs);
//对list进行打乱
Collections.shuffle(list);
System.out.println("============");
list.forEach(System.out::println);
System.out.println("============");
}
}