TreeMap sort by value

后端 未结 9 1082
闹比i
闹比i 2020-11-22 02:44

I want to write a comparator that will let me sort a TreeMap by value instead of the default natural ordering.

I tried something like this, but can\'t find out what

9条回答
  •  迷失自我
    2020-11-22 03:40

    I know this post specifically asks for sorting a TreeMap by values, but for those of us that don't really care about implementation but do want a solution that keeps the collection sorted as elements are added, I would appreciate feedback on this TreeSet-based solution. For one, elements are not easily retrieved by key, but for the use case I had at hand (finding the n keys with the lowest values), this was not a requirement.

      TreeSet> set = new TreeSet<>(new Comparator>()
      {
        @Override
        public int compare(Map.Entry o1, Map.Entry o2)
        {
          int valueComparison = o1.getValue().compareTo(o2.getValue());
          return valueComparison == 0 ? o1.getKey().compareTo(o2.getKey()) : valueComparison;
        }
      });
      int key = 5;
      double value = 1.0;
      set.add(new AbstractMap.SimpleEntry<>(key, value));
    

提交回复
热议问题