How can I separate a key or a value from a TreeSet<Map.Entry<key,value>>?

65 views Asked by At

I wrote this query and I need to return a list of sorted vehicles by the number of reservations. I made an occurrence map and sorted it by the number of occurrences from highest to lowest. The only problem is, I don't know how can I get the Vehicles out of the TreeSet.

public static void Q_GetAllVehiclesinTraveledReservationsSortedByAmountOfTimesTheyWereReserved(SysData sData){

    HashMap<Vehicle,Integer> occ=new HashMap<Vehicle,Integer>();
    Vehicle veh=null;
    TreeSet<Map.Entry<Vehicle,Integer>> sorted= new TreeSet<>(new Comparator<Map.Entry<Vehicle,Integer>>(){
        @Override
        public int compare(Entry<Vehicle, Integer> o1,
                Entry<Vehicle, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
        }
    });
    for(Location loc: sData.getLocations().values()){
        for(Reservation res: loc.getReservations().values()){
            if(res instanceof TraveledReservation){ 
                veh = ((TraveledReservation) res).getTrip().getCar();
                if(occ.containsKey(((TraveledReservation) res).getTrip().getCar())){    
                    int val=occ.get(veh);
                    occ.put(veh, ++val);
                }
                else{
                    occ.put(veh, 1);
                }
            }
        }
    }
    veh=null;
    sorted.addAll(occ.entrySet());
}
1

There are 1 answers

1
Raman Shrivastava On BEST ANSWER

Use this method:

public static List<Vehicle> getVehicles (TreeSet tSet) {
    List<Vehicle> vehicleList = new ArrayList<Vehicle>();
    Iterator itr = tSet.iterator();
    while(itr.hasNext()) {
        Entry<Vehicle, Integer> e = itr.next();
        vehicleList.add(e.getKey());
    }

    return vehicleList;
}

And call it like this:

List<Vehicle> vList = getVehicles(sorted);