How to iterate a HashMap using the natural entrySet() order?

前端 未结 6 623
醉酒成梦
醉酒成梦 2021-01-02 13:12

My Map contains keys sorted in alphabetical order. When I display it, I\'m using entrySet().iterator(), but my results are not in the alphabetical order. How can I get my re

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 13:33

    For anyone finding this question in 2020 and beyond...
    Now that we have streams, you can do something like this:

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

提交回复
热议问题