gpt4 book ai didi

java - TreeSet 使用比较器排序问题

转载 作者:行者123 更新时间:2023-12-01 19:43:52 25 4
gpt4 key购买 nike

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

我想这样做:

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。

最佳答案

仅仅因为没有构造函数可以一次性完成所有操作,并不意味着您不能用两行代码完成所有操作。

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

关于java - TreeSet<Entry<Character, Long> 使用比较器排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54306158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com