本文主要是介绍集合9、集合_Map接口_TreeMap类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
TreeMap的排序方式
package map;
import org.junit.jupiter.api.Test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
/**
* @author HUTAO
* @Description
* @date 2021/10/23 16:45
*/
public class TreeMapTest {
//向TreeMap中添加key-value,要求key必须是由同一个类创建的对象
//自然排序
@Test
public void test1() {
TreeMap map = new TreeMap();
User u1 = new User("Tom", 15);
User u2 = new User("Jake", 23);
User u3 = new User("Roy", 22);
User u4 = new User("Andy", 18);
map.put(u1, 98);
map.put(u2, 96);
map.put(u3, 95);
map.put(u4, 100);
Set entrySet = map.entrySet();
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()) {
System.out.println(iterator2.next());
}
}
//定制排序
@Test
public void test2() {
TreeMap map = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof User && o2 instanceof User) {
User u1 = (User) o1;
User u2 = (User) o2;
return Integer.compare(u1.getAge(), u2.getAge());
}
throw new RuntimeException("输入的类型不匹配!");
}
});
User u1 = new User("Tom", 15);
User u2 = new User("Jake", 23);
User u3 = new User("Roy", 22);
User u4 = new User("Andy", 18);
map.put(u1, 98);
map.put(u2, 96);
map.put(u3, 95);
map.put(u4, 100);
Set entrySet = map.entrySet();
Iterator iterator2 = entrySet.iterator();
while (iterator2.hasNext()) {
System.out.println(iterator2.next());
}
}
}
这篇关于集合9、集合_Map接口_TreeMap类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!