package cnki.bdmsjob;
import java.util.*;
import java.util.stream.Collectors;
/**
* User: qc
* Date: 9:43 2021/1/21
* Description: No Description
* Version 1.0
*/
public class SynTest {
public static void main(String[] args) {
Map<Key,String> map = new HashMap<>();
Key k1=new Key(1);
Key k2=new Key(2);
Key k3=new Key(3);
Key k4=new Key(4);
Key k5=new Key(1);
map.put(k2,"k2");
map.put(k1,"k1");
map.put(k4,"k4");
map.put(k3,"k3");
map.put(k5,"k5");
System.out.println(map);
//hashmap倒序排列
LinkedHashMap<Key, String> collect = map.entrySet().stream().sorted(( o1, o2 ) -> o2.getValue().compareTo(o1.getValue())).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, ( v1, v2 ) -> v1, LinkedHashMap::new));
System.out.println(collect.toString());
//求排序好的前n map值
List<String> list = map.entrySet().stream().sorted(( o1, o2 ) -> o2.getValue().compareTo(o1.getValue())).map(Map.Entry::getValue).
collect(Collectors.toList()).subList(0, 3);
System.out.println(list.toString());
}
}
class Key{
private Integer id;
public Key( Integer id ) {
this.id = id;
}
public Integer getId() {
return id;
}
//自定义的map key需要重写hashcode和equals
@Override
public boolean equals( Object o ) {
if (this == o) return true;
if (!(o instanceof Key)) return false;
Key key = (Key) o;
return getId().equals(key.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
/* @Override
public boolean equals( Object o ) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return Objects.equals(id, key.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}*/
}