目录
TreeMap
- 按key排序生成map可以有TreeMap 完成,TreeMap可以按key的自然顺序排序(Comparable实现)
lambda comparingByKey
- 使用lambda也可以很方便的对map排序
- Map.Entry.comparingByKey() 按key排序的Comparator
- Map.Entry.comparingByValue()按value排序的Comparator
- 转载于 点击跳转
示例代码
- 如下
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class MapSortDemo {
public static void main(String[] args) {
User user1 = new User("zs", 10);
User user2 = new User("ls", 5);
User user3 = new User("wu", 20);
Map<String, User> map = new HashMap<>();
map.put(user1.getName(), user1);
map.put(user2.getName(), user2);
map.put(user3.getName(), user3);
System.out.println("------map sort by key------");
map.entrySet().
stream().
sorted(Map.Entry.comparingByKey()).
forEach(System.out::println);
System.out.println("------map sort by value------");
map.entrySet().
stream().
sorted(Map.Entry.comparingByValue()).
forEach(System.out::println);
System.out.println("------return sorted by key map ------");
TreeMap<String,User> treeMap=new TreeMap<>(map);
System.out.println(treeMap);
System.out.println("------return sorted by value map ------");
Map<String, User> result = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println(result);
}
}
class User implements Comparable<User> {
public User(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(User o) {
return this.getAge() - o.getAge();
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 输出
------map sort by key------
ls=User{name='ls', age=5}
wu=User{name='wu', age=20}
zs=User{name='zs', age=10}
------map sort by value------
ls=User{name='ls', age=5}
zs=User{name='zs', age=10}
wu=User{name='wu', age=20}
------return sorted by key map ------
{ls=User{name='ls', age=5}, wu=User{name='wu', age=20}, zs=User{name='zs', age=10}}
------return sorted by value map ------
{ls=User{name='ls', age=5}, zs=User{name='zs', age=10}, wu=User{name='wu', age=20}}
标签:map,HashMap,lambda,Map,age,User,------,排序,name
From: https://www.cnblogs.com/Twittery/p/17728246.html