/**
* 写一个方法,传给该方法一个HashMap<Integer,User>参数,
* 要求按照该hashMap的User的age的倒序排序,返回一个HashMap或者其子类。
* User 有age 和name属性。
*/
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.Map.Entry;
public class ShortHashMap {
public static void main(String[] args) {
HashMap<Integer, User> map = new HashMap<Integer, User>();
map.put(1, new User(1, "zhang1"));
map.put(3, new User(3, "zhang3"));
map.put(2, new User(2, "zhang2"));
printMap(shortHashMap(map));
}
/**
* map排序方法
* @param map
* @return
*/
public static HashMap<Integer, User> shortHashMap(HashMap<Integer, User> map) {
// 通过TreeSet给entrySet排序后再生成LinkedHashMap
TreeSet<Entry<Integer, User>> ts = new TreeSet<Entry<Integer, User>>(
new UserEntryConpartor());
for (Entry<Integer, User> mapEntry : map.entrySet()) {
ts.add(mapEntry);
}
return setToMap(ts);
}
/**
* EntrySet转成Map
* @param ts
* @return
*/
public static LinkedHashMap<Integer, User> setToMap(
TreeSet<Entry<Integer, User>> ts) {
LinkedHashMap<Integer, User> hm = new LinkedHashMap<Integer, User>();
for (Entry<Integer, User> e : ts) {
hm.put(e.getKey(), e.getValue());
}
return hm;
}
public static void printMap(Map<? extends Object, ? extends Object> map) {
for(Entry<? extends Object, ? extends Object> entry:map.entrySet()){
System.out.println("Key: "+entry.getKey()+"---Val: "+entry.getValue());
}
}
}
class UserEntryConpartor implements Comparator<Entry<Integer, User>> {
@Override
public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {
return -o1.getValue().compareTo(o2.getValue());
}
}
--------------------------------------------
import java.io.Serializable;
public class User implements Serializable, Comparable<User> {
private static final long serialVersionUID = 1L;
private int age;
private String name;
public User() {
}
public User(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (age != other.age)
return false;
return true;
}
@Override
public String toString() {
return "User [age=" + age + ", name=" + name + "]";
}
@Override
public int compareTo(User o) {
return this.getAge() == o.getAge() ? this.getName().compareTo(
o.getName()) : this.getAge() - o.getAge();
}
}
|