简体   繁体   中英

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.

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. 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.

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.

PS: Comparing values using - is bad idea. You better use Integer.compare or create comparator using Comparator.comparing(Entry::getValue) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM