一、HashMap按照value排序
HashMap
HashMap是一个数组和链表组成的一种链表散列结构,存储方式是根据key的hash值来决定存储的位置,这就导致了存储后的元素不会维持插入时的顺序。
Comparator
如果我们需要控制某个类的次序并且该类本身不支持排序,那么就可以建立一个类比较器来进行排序,实现方式很简单只需要实现java.util.Comparator接口。
Collections.sort
Collections.sort(List list,new Comparator(){
@override
public int compare( o1, o2){
return 0;
}
});
表示对传入的list进行排序,排序方法需要在comparator接口中重写,按return值进行排序,小于0降序,大于0升序
,一般是对o1和o2两个对象的某个属性进行比较得出结果。
实现
实现原理
由于HashMap不属于list子类,所以无法使用Collections.sort方法来排序,所以我们将hashmap中的entryset取出放入一个ArrayList中,来对ArrayList中的entryset进行排序(根据entryset的值),达到我们对hashmap的值进行排序的效果。
代码
import java.util.*;
public class test{
public static void main(String[] args) {
//产生一个map并添加一些参数
Map<String,Integer> map = new HashMap<>();
map.put("ddd", 1);
map.put("aaa", 2);
map.put("bbb", 3);
map.put("ccc", 4);
List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet()); //将map的entryset放入list集合
//对list进行排序,并通过Comparator传入自定义的排序规则
Collections.sort(list,new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue() - o2.getValue(); //重写排序规则,小于0表示升序,大于0表示降序
}
});
//用迭代器对list中的键值对元素进行遍历
Iterator<Map.Entry<String, Integer>> iter = list.iterator();
while(iter.hasNext()){
Map.Entry<String, Integer> item = iter.next();
String key = item.getKey();
int value = item.getValue();
System.out.println("键"+key+"值"+value);
}
}
}
二、ArrayList使用自定义comparator
import java.sql.Struct;
import java.util.*;
public class test{
public static void main(String[] args) {
List<Student> stu=new ArrayList<>();
Student s1=new Student(30,"test1");
Student s2=new Student(20,"test2");
Student s3=new Student(60,"test3");
stu.add(s1);
stu.add(s2);
stu.add(s3);
Collections.sort(stu, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.age-o2.age;
}
});
for(int i=0;i<stu.size();i++){
System.out.println(stu.get(i).name);
}
}
}
class Student{
public int age;
public String name;
public Student(int age,String name){
this.age=age;
this.name=name;
}
}