Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
1
Indexable
Never
Map<Integer, Integer> findTopToKeepDatasorted(List<Entry> list) {
        HashMap<Integer, PlaceCount> ref = new HashMap(); //
        HashMap<Integer, TreeSet<PlaceCount>> inMemoryStruct = new HashMap();
        for(Entry entry: list){
            int postalCode = entry.postalCode;
            int placeId = entry.placeId;
            inMemoryStruct.putIfAbsent(postalCode, new TreeSet<>());
            TreeSet<PlaceCount> placeCounts = inMemoryStruct.get(postalCode);
            ref.putIfAbsent(placeId, new PlaceCount(placeId, 0));
            PlaceCount placeCount1 = ref.get(placeId);
            placeCounts.remove(placeCount1);
            placeCount1.count++;
            placeCounts.add(placeCount1);
            inMemoryStruct.put(postalCode, placeCounts);
        }
        Set<Map.Entry<Integer, TreeSet<PlaceCount>>> entries = inMemoryStruct.entrySet();

        Map<Integer, Integer> ans = new HashMap<>();
        for(Map.Entry<Integer, TreeSet<PlaceCount>> e:inMemoryStruct.entrySet()){
            ans.put(e.getKey(), e.getValue().pollLast().placeId);
        }
        return ans;
    }

class PlaceCount implements Comparable<PlaceCount>{
    int placeId;
    int count;

    PlaceCount(int placeId, int count){
        this.count = count;
        this.placeId = placeId;
    }

    @Override
    public int compareTo(PlaceCount o) {
        if(o.placeId == this.placeId) {
            return 0;
        }
        return count-o.count;
    }
}