import java.util.LinkedHashMap;
public class demo {
public static void main(String[] args) {
LinkedHashMap<String,Integer>lkd=new LinkedHashMap<>();
lkd.put("pp",16);
lkd.put("aa",15);
lkd.put("cc",12);
lkd.put("cc",13);
//覆盖 有序
System.out.println(lkd);
}
}
import java.util.Comparator;
import java.util.TreeMap;
public class demo {
public static void main(String[] args) {
//1.底层为TreeMap为升序
//创建集合
//降序new Comparator
TreeMap<Integer,String>tm=new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
//o1准备添加的元素 o2为已经在红黑树中的元素
//降序
return o2-o1;
}
});
//添加元素
tm.put(1,"qqq");
tm.put(2,"www");
tm.put(3,"eee");
tm.put(5,"rrr");
tm.put(4,"aaa");
System.out.println(tm);
}
}
上面第一问 下面第二问
public class student implements Comparable<student>{
private String name;
private int age;
public student() {
}
public student(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "student{name = " + name + ", age = " + age + "}";
}
@Override
public int compareTo(student o) {
//this为当前要添加元素 o为已经在红黑树中的元素
//按照年龄升序来排列的
int i=this.getAge()-o.getAge();
//年龄一样按照姓名字母排列
i=i==0? this.getName().compareTo(o.getName()):i;
return i;
}
}
import java.util.TreeMap;
public class demo {
public static void main(String[] args) {
//创建集合
TreeMap<student,String>tm=new TreeMap<>();
//创建学生对象
student s1=new student("qqq",21);
student s2=new student("www",22);
student s3=new student("eee",23);
//添加元素
tm.put(s1,"河南");
tm.put(s2,"南京");
tm.put(s3,"江苏");
System.out.println(tm);
}
}
import java.util.TreeMap;
import java.util.function.BiConsumer;
public class demo {
public static void main(String[] args) {
//定义字符串
String s="abcdeabbcdeeda";
//定义集合treemap 因为这个题目最后要排序 所以用treemap 不排序用hashmap
TreeMap<Character,Integer>tm=new TreeMap<>();
//遍历字符串
for (int i = 0; i < s.length(); i++) {
//获取每个字符
char c = s.charAt(i);
//判断字符是否存在
if (tm.containsKey(c)){
//获取这个值
Integer count = tm.get(c);
//值进行加一
count++;
//再放入集合中
tm.put(c,count);
}else{
//不存在 第一次就直接赋值
tm.put(c,1);
}
}
//改最后输出格式
StringBuilder sb=new StringBuilder();
//lambda遍历
tm.forEach(( key, value) -> sb.append(key).append("(").append(value).append(")"));
System.out.println(sb);
}
}