Sorting a TreeMap by object properties

57 Views Asked by At

I have a TreeMap full of Houses. Each house has different properties such as address, number of floors, etc. The TreeMap gets populated into a JList so that the user can select a house from the list, and then view each property in its own respective field. Before the list is open, the user has the option to sort by various different ways such as House addresses alphabetically, or by highest number of bedrooms etc and then they will view the list of Houses in that order.

I understand that TreeMaps are sorted by their keys. I am trying to use Comparator but I feel like I've hit a wall and I have no idea if I'm doing this correctly. How can I call my Comparator from the JFrame/JList that I am using?

Can anyone help me out please? My instructor hasn't responded to my email in 4 days so I am stuck.

public static Map<String, House> neighborhood;

public Neighborhood(){
neighborhood = new TreeMap<>();
}

    public static class SortByAddress implements Comparator<Map.Entry<String, House>>{
        @Override
        public int compare(Entry<String, House> o1, Entry<String, House> o2) {
            // TODO Auto-generated method stub
                return o1.getValue().getAddress().toString().compareTo(o2.getValue().getAddress().toString());
        }
        
    }
1

There are 1 best solutions below

0
Basil Bourque On

You only care about the values of your map, the House objects. So extract.

Collection < House > houses = myMap().values() ;

Make a sortable list from that collection.

List < House > housesSorted = new ArrayList<>( houses );

Define your various comparators.

Comparator < House > compareByBedroomCount = Comparator.comparing( House :: bedroomCount ) ;
Comparator < House > compareBySquareMeters = Comparator.comparing( House :: squareMeters ) ;

Apply the appropriate comparator.

housesSorted.sort( compareByBedroomCount );