一:
package com.imut.treemap;
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
//需求1:键:id (String);值:商品名称(字符串)
//要求: 按照id的降序排列
//1、创建TreeMap集合
TreeMap<String,String> map=new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int result=o2.compareTo(o1);
return result;
}
});
//2、在集合中添加对象
map.put("bfe", "巧克力");
map.put("aab", "苏打水");
map.put("bar", "牛奶");
map.put("efg", "面包");
map.put("aaa", "咖啡");
//打印集合
System.out.println(map);
二:
/*
//需求1:键:id (整数);值:商品名称(字符串)
//要求: 按照id的降序排列
//1、创建TreeMap集合
TreeMap<Integer,String> map=new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
int result=o2-o1;
return result;
}
});
//2、在集合中添加对象
map.put(5, "巧克力");
map.put(2, "苏打水");
map.put(4, "牛奶");
map.put(3, "面包");
map.put(1, "咖啡");
//打印集合
System.out.println(map);
*/
三:
/*
//需求1:键:id (整数);值:商品名称(字符串)
//要求:按照id的升序排列; 按照id的降序排列
//1、创建TreeMap集合
TreeMap<Integer,String> map=new TreeMap<>();
//2、在集合中添加对象
map.put(5, "巧克力");
map.put(2, "苏打水");
map.put(4, "牛奶");
map.put(3, "面包");
map.put(1, "咖啡");
//打印集合
System.out.println(map);
*/
}
}
3187

被折叠的 条评论
为什么被折叠?



