[英]TreeSet<Entry<Character, Long> sort using comparator problem
我想在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());
您必須先創建集合
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)
創建比較器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.