【问题标题】:TreeSet<Entry<Character, Long> sort using comparator problemTreeSet<Entry<Character, Long> 使用比较器问题排序
【发布时间】:2019-01-22 10:26:15
【问题描述】:

我想在 Java 11 中对 TreeSet 进行排序。 我尝试使用比较器,但问题是 lambda 表达式不将 args 视为条目。

我想这样做:

SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(map.entrySet(), 
    ((o1, o2) -> (int) (o1.getValue() - o2.getValue())));

但问题是 TreeSet 中没有这样的构造函数。所以我尝试了另一个程序:

SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(map.entrySet())
    .comparator()
    .compare(o1,o2)

比较方法需要的参数:

compare(capture of ? super Entry<Character, Long> o1, capture of ? super Entry<Character, Long> o1)

但我不知道我必须传递哪些参数而不是 o1,o2。

【问题讨论】:

  • o1.getValue() AND o2.getValue() ???
  • @nafas o1 和 o2 未在此范围内定义。 compare 方法给出两个参数: compare(capture of ? super Entry o1, capture of ? super Entry o1)

标签: java sorting generics comparator treeset


【解决方案1】:

仅仅因为没有构造函数可以一次完成,并不意味着你不能在 2 行中完成。

SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(Comparator.comparingLong(Entry::getValue));
sortedSet.addAll(map.entrySet());

【讨论】:

  • 或者让Map.Entry.comparingByValue()new TreeSet&lt;&gt;(Map.Entry.comparingByValue())一样创建比较器。
【解决方案2】:

你必须先创建集合

SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>((o1, o2) -> (int) (o1.getValue() - o2.getValue()));

然后添加元素

sortedSet.addAll(map.entrySet());

TreeSet 创建后无法设置比较器。

PS:使用- 比较值是个坏主意。您最好使用Integer.compare 或使用Comparator.comparing(Entry::getValue) 创建比较器。

【讨论】:

  • 虽然这解决了 OP 的问题,但请注意不要仅将数字与减号运算符进行比较。可能会出现溢出错误,尤其是考虑到您将长结果转换为 int。更好地与 Comparator.comparing(Entry::getValue) 进行比较
  • @talex 不要使用minus 作为比较器;有Long::compare
  • @kumesana 是的,会添加注释。
  • @kumesana 最好使用Comparator.comparingLong(Entry::getValue)
  • @jbx 我不在乎使用哪个。为什么你认为它更好?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 2013-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多