Java TreeSet<;进入<;长字符>;用比较器排序问题
我想对Java11中的树集进行排序。 我尝试使用比较器,但问题是lambda表达式不考虑ARGS作为输入。 我想这样做:Java TreeSet<;进入<;长字符>;用比较器排序问题,java,sorting,generics,comparator,treeset,Java,Sorting,Generics,Comparator,Treeset,我想对Java11中的树集进行排序。 我尝试使用比较器,但问题是lambda表达式不考虑ARGS作为输入。 我想这样做: SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(map.entrySet(), ((o1, o2) -> (int) (o1.getValue() - o2.getValue()))); SortedSet SortedSet=新树集(map.entr
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(map.entrySet(),
((o1, o2) -> (int) (o1.getValue() - o2.getValue())));
SortedSet SortedSet=新树集(map.entrySet(),
((o1,o2)->(int)(o1.getValue()-o2.getValue());
但问题是TreeSet中没有这样的构造函数。所以我尝试了另一个程序:
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(map.entrySet())
.comparator()
.compare(o1,o2)
SortedSet-SortedSet=新树集(map.entrySet())
.比较国()
.比较(o1,o2)
比较方法所需参数:
compare(capture of ? super Entry<Character, Long> o1, capture of ? super Entry<Character, Long> o1)
比较(捕获超级条目o1,捕获超级条目o1)
但是我不知道我必须传递什么参数来代替o1,o2。你必须先创建集合
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>((o1, o2) -> (int) (o1.getValue() - o2.getValue()));
创建TreeSet
后,无法设置比较器
PS:使用
-
比较值是个坏主意。您最好使用整数。比较或使用比较器创建比较器。比较(Entry::getValue)
您必须首先创建集合
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>((o1, o2) -> (int) (o1.getValue() - o2.getValue()));
创建TreeSet
后,无法设置比较器
PS:使用-
比较值是个坏主意。最好使用Integer。比较或使用comparator创建comparator。比较(Entry::getValue)
仅仅因为没有构造函数一次完成所有操作,并不意味着不能在两行内完成
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(Comparator.comparingLong(Entry::getValue));
sortedSet.addAll(map.entrySet());
SortedSet-SortedSet=新树集(Comparator.comparingLong(Entry::getValue));
sortedSet.addAll(map.entrySet());
仅仅因为没有构造函数一次完成所有工作,并不意味着不能在两行中完成
SortedSet<Entry<Character, Long>> sortedSet = new TreeSet<>(Comparator.comparingLong(Entry::getValue));
sortedSet.addAll(map.entrySet());
SortedSet-SortedSet=新树集(Comparator.comparingLong(Entry::getValue));
sortedSet.addAll(map.entrySet());
o1.getValue()和o2.getValue()??@nafas o1和o2未在此范围内定义。compare方法提供了两个参数:compare(捕获超级条目o1,捕获超级条目o1)o1.getValue()和o2.getValue()?@nafas o1和o2未在此范围内定义。compare方法给出了两个参数:compare(捕获超级条目o1,捕获超级条目o1)。这解决了OP的问题,但要注意,不要只使用减号运算符来比较数字。可能会出现溢出错误,特别是考虑到您要将一个长结果转换为int。最好与Comparator进行比较。Comparating(Entry::getValue)@talex不使用减号作为Comparator;有Long::compare
@kumesana是的,将添加注释。@kumesana最好使用Comparator。comparingLong(Entry::getValue)
@jbx我不在乎使用哪个。为什么你认为它更好?虽然这解决了OP的问题,但要小心,不要用一个负号来比较数字。可能会出现溢出错误,特别是考虑到您要将一个长结果转换为int。最好与Comparator进行比较。Comparating(Entry::getValue)@talex不使用减号作为Comparator;有Long::compare
@kumesana是的,将添加注释。@kumesana最好使用Comparator。comparingLong(Entry::getValue)
@jbx我不在乎使用哪个。为什么你认为它更好?或者让Map.Entry.comparingByValue()
创建比较器,比如newtreeset(Map.Entry.comparingByValue())
。或者让Map.Entry.comparingByValue()
创建比较器,比如newtreeset(Map.Entry.comparingByValue())
。