Get smallest available key (>= 1) in a HashMap

Related searches

I am using a Map in which I save all tracks that the user registers. Every new track should be assigned a new ID which starts at 1. However, if tracks 1, 2, 3, 4 exist and the user deletes track with ID 1 the next added track gets the smallest available ID >=1 which in this case would be 1.

How is it possible to do this efficiently? Or is there a better datatype available?

private Map<Integer, Track> tracks;

public Register() {
    this.trains = new HashMap<>();
}

public void addTrack(Track track) {
    int id = <get Smallest Value Available >= 1>;
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + id + " doesn't exist.");
    }
}

Approach 1: You can use TreeMap and iterate through its keys, and if there is a gap between two keys, you can insert your element in this gap. Addition will work in O(currentKeysCount) worst-case, deletion will work in O(log(currentKeysCount)).

private TreeMap<Integer, Track> tracks;

public Register() {
    this.trains = new TreeMap<>();
}

public void addTrack(Track track) {
    int id = 1;
    for (int key : this.trains.keySet) {
        if (key > id) break;
        id = key + 1;
    }
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}

Approach 2: You can create a PriorityQueue that will store deleted keys. Addition and deletion will work in O(log(currentKeysCount) + log(deletedKeysCount)).

private Map<Integer, Track> tracks;
private PriorityQueue<Integer> deletedKeys;
private int nextKey;

public Register() {
    this.trains = new HashMap<>();
    this.deletedKeys = new PriorityQueue<>();
    this.nextKey = 0;
}

public void addTrack(Track track) {
    int id = nextKey;
    if (!deletedKeys.isEmpty()) id = deletedKeys.poll();
    this.tracks.put(id, track);
}

public void removeTrack(int id) {
    if (tracks.containsKey(id)) {
        this.tracks.remove(id);
        this.deletedKeys.add(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}

Approach 3: It may be much easier to ignore missing keys and just increase nextKey counter on every addition (you can even use long instead of int). Unless you add a new key more often than once per millisecond, your program won't fail earlier than all code that uses System.currentTimeMillis() (and it will fail in more than 292 million years). Addition and deletion will work in O(log(currentKeysCount))

Get smallest available key (>= 1) in a HashMap, Get smallest available key (>= 1) in a HashMap. 发布于 2020-05-03 06:55:45. I am using a Map in which I save all tracks that the user registers. Every new track � Use the flashlight to find the key hole at night. Impromptu happy hour? Buy Three, Get Two Free! Save $119.98 USD! $299.95 USD $179.97 USD. 3 KeySmart™ Pro with

I would do it with a loop and see if the which value is not yet included in the map

public Integer getId(Map<Integer, Track> tracks) {
    // Set on max-value
    Integer id = Collections.max(tracks.keySet()) + 1;

    for (int i = 1; i <= tracks.keySet().size(); i++) {
        if (!tracks.keySet().contains(i)) {
            // lower value available
            id = i;
            break;
        }
    }

    return id;
}

min-key - clojure.core, Available since 1.0 (source) we have a list of key colours ;; We want to find the one closest to a supplied colour ;; We're storing rgb values as [r g b] ;; use min- key to find colour that minimizes ;; the euclidean distance between the supplied� For products that are available for download from the Microsoft Volume Licensing Service Center (VLSC ) Web site, the setup key is provided on the download screen. Microsoft Activation Center. You can call the Activation Call Center to obtain the setup keys you need.

The most efficient way will be to use SortedMap as you won't need to find the smallest available key. The smallest available key will be always located at the beginning of the Map. You can use SortedMap::firstKey to get the smallest key.

Get lowest and highest key stored in Java TreeMap example, This Java Example shows how to get the lowest and highest key stored in the java TreeMap object using firstKey and lastKey methods of java� To get a Valorant beta key, you will need a Riot account, but you also need to sign up for Twitch. You must also be located in one of the regions listed later in this section. Follow the step-by

Say if from 100 trains number 40 and number 60 are free, you want to get 40 from {40, 60}.

private final Map<Integer, Track> tracks = new HashMap<>();;
private final SortedSet<Integer> freeIds = new TreeSet<>();

public synchronized void addTrack(Track track) {
    int id;
    if (freeIds.isEmpty()) {
        id = 1 + tracks.size(); // Numbering from 1
    } else {
        id = freeIds.first();
        freeIds.remove(id);
    }
    track.setId(id);
    tracks.put(id, track);
}

public synchronized void removeTrack(int id) {
    Track track = tracks.remove(id);
    if (track != null) {
        track.setId(-1);
        freeIds.add(id);
    } else {
        Terminal.printError("track with ID " + track.getId() + " doesn't exist.");
    }
}

Nut F6 Mini the world Smallest Smart Trackers, Buy Nut F6 Mini the world Smallest Smart Trackers: GPS Trackers - Amazon.com ✓ FREE DELIVERY One touch find: call nut by pressing the "Beep" button on nut app, nut will beep for you to find it. Date First Available, January 24, 2016� After a misstep last year, Apple is back on top with what is simply the best smaller phone available. The iPhone 11 Pro has longer battery life, a better screen and excellent performance all round.

Python: Get the maximum and minimum value in a dictionary , my_dict = {'x':500, 'y':5874, 'z': 560} key_max = max(my_dict.keys(), min( my_dict.keys(), key=(lambda k: my_dict[k])) print('Maximum Value: '� Get Windows Product License Information (including product key) GUI Tool Windows License Extractor is a small PowerShell/WinForms GUI tool (Sapien PowerShell Studio 2015) that will help you to display/export licensing information (including the product key where possible) for your current running operating system, as well as other remote computers.

4 Key Strategies Small Retailers Need for a Healthy Business Have customers be able to purchase on the platform or get a shipping or sales discount when they buy from your website. 3. Have a

Testing “as many people as possible” is vital to helping fight the coronavirus pandemic, 11 directors of some of the various National Institutes of Health said Tuesday.

Comments
  • This solution looks for me: stackoverflow.com/questions/18345131/…
  • I don't need the smallest saved value. I want to prevent gaps when deleting a track. E. g. tracks 1, 2, 3 exist. The user deletes track 2. Then he adds another track that gets ID 2
  • You will get unpopular fast if you first post, then within 7 minutes answer and then shortly after delete (for another Q/A).
  • I don't need the smallest saved value. I want to prevent gaps when deleting a track. E. g. tracks 1, 2, 3 exist. The user deletes track 2. Then he adds another track that gets ID 2
  • @LudwigvonDrake Yes, i know. First you remove the track from the map and then you call the "getId" method, which determines the current lowest Id.
  • I don't need the smallest saved value. I want to prevent gaps when deleting a track. E. g. tracks 1, 2, 3 exist. The user deletes track 2. Then he adds another track which gets ID 2.
  • Even if you do not need to know the smallest key in the SortedMap, you can iterate the EntrySet of the SortedMap for value 1 to the highest ID and break at the missing value. I hope you don't need any help to put this logic into code.