Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort Tree Map with Lambda Comparator

I have below class

public class Frequency {
    public int freq;
    public int val;
}

I want to sort the the TreeMap with Frequence.freq
How to do it.

TreeMap<Integer,Frequency> map = new TreeMap( (f1,f2) ->  f1. ) ; 

// not able to access f1.freq /Frequency class variables arent visible

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

TreeMap keys are always sorted it means that this collection will not let you change the order. If you want to get sorted collection by freq value you can do something like:

public static void main(String[] args) {
        Map<Integer, Frequency> map = ....;

        List<Frequency> sortedList = map.values().stream().sorted(Comparator.comparingInt(o -> o.freq)).collect(toCollection(ArrayList::new));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading