如何从TreeSet <map.entry <key,value>&gt;?中分离键或值?

时间:2015-06-21 15:14:08

标签: java treeset

我写了这个查询,我需要按预订数量返回已排序车辆的列表。我制作了一个发生图,并按照从最高到最低的出现次数进行排序。唯一的问题是,我不知道如何从Vehicle中获取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 个答案:

答案 0 :(得分:1)

使用此方法:

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;
}

并称之为:

List<Vehicle> vList = getVehicles(sorted);