对HashMap进行排序

目录

 

初始化数据

通过TreeMap

通过ArrayList

对Key进行排序

对Value进行排序

通过Lambdas and Streams

对Key进行排序

 对Value进行排序


初始化数据

Map map = new HashMap<>();
 
Employee employee1 = new Employee(1L, "Mher");
map.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map.put(employee4.getName(), employee4);

另外需要注意一下Employee是实现了Comparable接口的

public class Employee implements Comparable {
 
    private Long id;
    private String name;
 
    // constructor, getters, setters
 
    // override equals and hashCode
    @Override
    public int compareTo(Employee employee) {
        return (int)(this.id - employee.getId());
    }
}

通过TreeMap

TreeMap sorted = new TreeMap<>(map);
// or
TreeMap sorted = new TreeMap<>();
sorted.putAll(map);

输出结果

Annie=Employee{id=22, name='Annie'}
George=Employee{id=2, name='George'}
John=Employee{id=8, name='John'}
Mher=Employee{id=1, name='Mher'}

通过ArrayList

对Key进行排序

List employeeByKey = new ArrayList<>(map.keySet());
Collections.sort(employeeByKey);

输出:[Annie, George, John, Mher]

对Value进行排序

List employeeById = new ArrayList<>(map.values());
Collections.sort(employeeById);

通过Lambdas and Streams

对Key进行排序

map.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByKey())
  .forEach(System.out::println);

输出结果

Annie=Employee{id=22, name='Annie'}
George=Employee{id=2, name='George'}
John=Employee{id=8, name='John'}
Mher=Employee{id=1, name='Mher'}

 对Value进行排序

map.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByValue())
  .forEach(System.out::println)

输出结果

Mher=Employee{id=1, name='Mher'}
George=Employee{id=2, name='George'}
John=Employee{id=8, name='John'}
Annie=Employee{id=22, name='Annie'}

可以将排序后的结果放到一个新的Map集合中

Map result = map.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByValue())
  .collect(Collectors.toMap(
    Map.Entry::getKey, 
    Map.Entry::getValue, 
    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 

你可能感兴趣的:(Java集合,HashMap,stream,lambda)