[英]TreeSet<Entry<Character, Long> sort using comparator problem
I want to Sort a TreeSet in Java 11. I tried using a comparator, but the problem is lambda expression does not consider args as Entry. 我想在Java 11中对TreeSet进行排序。我尝试使用比较器,但问题是lambda表达式未将args视为Entry。
I wanted to do this: 我想这样做:
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(map.entrySet(),
((o1, o2) -> (int) (o1.getValue() - o2.getValue())));
but the problem is there's no such constructor in TreeSet. 但是问题是TreeSet中没有这样的构造函数。 So I tried another procedure: 所以我尝试了另一个过程:
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(map.entrySet())
.comparator()
.compare(o1,o2)
compare method needed parameter: 比较方法所需参数:
compare(capture of ? super Entry<Character, Long> o1, capture of ? super Entry<Character, Long> o1)
but I don't know what arguments I have to pass instead of o1,o2. 但我不知道要传递什么参数而不是o1,o2。
Just because there is no constructor to do it all at once, doesn't mean you can't do it in 2 lines. 仅仅因为没有构造函数可以一次完成所有操作,并不意味着您不能分两行进行操作。
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(Comparator.comparingLong(Entry::getValue));
sortedSet.addAll(map.entrySet());
You have to create set first 您必须先创建集合
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>((o1, o2) -> (int) (o1.getValue() - o2.getValue()));
and then add elements 然后添加元素
sortedSet.addAll(map.entrySet());
There is no way to set comparator after TreeSet
is created. 创建TreeSet
之后,无法设置比较器。
PS: Comparing values using -
is bad idea. PS:使用-
比较值是个坏主意。 You better use Integer.compare
or create comparator using Comparator.comparing(Entry::getValue)
. 您最好使用Integer.compare
或使用Comparator.comparing(Entry::getValue)
创建比较器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.