Java HashMap - How to simultaneously get and then remove a random entry from a HashMap?











up vote
1
down vote

favorite












I was wondering if it is possible to get a random value from a HashMap and then straight after remove that key/value from the HashMap? I can't seem to find any method that works, would a different data structure be more appropriate for this?



Edit:
I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.










share|improve this question
























  • By simply calling the remove(key) that will remove the element with that key.
    – imprezzeb
    Nov 11 at 4:49










  • What do you mean by a random entry? By whom will the random entry be chosen?
    – Kevin Anderson
    Nov 11 at 4:52












  • I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.
    – JennaTools
    Nov 11 at 4:58










  • Use .keySet method on HashMap to obtain all the existing keys as a Set; use .toArray method on the key set to get an array of the keys. Generate a random number between zero and the size of the key array; get the key k at that index, use .remove(k) on the HashMap.
    – Kevin Anderson
    Nov 11 at 5:04

















up vote
1
down vote

favorite












I was wondering if it is possible to get a random value from a HashMap and then straight after remove that key/value from the HashMap? I can't seem to find any method that works, would a different data structure be more appropriate for this?



Edit:
I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.










share|improve this question
























  • By simply calling the remove(key) that will remove the element with that key.
    – imprezzeb
    Nov 11 at 4:49










  • What do you mean by a random entry? By whom will the random entry be chosen?
    – Kevin Anderson
    Nov 11 at 4:52












  • I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.
    – JennaTools
    Nov 11 at 4:58










  • Use .keySet method on HashMap to obtain all the existing keys as a Set; use .toArray method on the key set to get an array of the keys. Generate a random number between zero and the size of the key array; get the key k at that index, use .remove(k) on the HashMap.
    – Kevin Anderson
    Nov 11 at 5:04















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I was wondering if it is possible to get a random value from a HashMap and then straight after remove that key/value from the HashMap? I can't seem to find any method that works, would a different data structure be more appropriate for this?



Edit:
I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.










share|improve this question















I was wondering if it is possible to get a random value from a HashMap and then straight after remove that key/value from the HashMap? I can't seem to find any method that works, would a different data structure be more appropriate for this?



Edit:
I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.







java dictionary hashmap






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 5:00

























asked Nov 11 at 4:44









JennaTools

133




133












  • By simply calling the remove(key) that will remove the element with that key.
    – imprezzeb
    Nov 11 at 4:49










  • What do you mean by a random entry? By whom will the random entry be chosen?
    – Kevin Anderson
    Nov 11 at 4:52












  • I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.
    – JennaTools
    Nov 11 at 4:58










  • Use .keySet method on HashMap to obtain all the existing keys as a Set; use .toArray method on the key set to get an array of the keys. Generate a random number between zero and the size of the key array; get the key k at that index, use .remove(k) on the HashMap.
    – Kevin Anderson
    Nov 11 at 5:04




















  • By simply calling the remove(key) that will remove the element with that key.
    – imprezzeb
    Nov 11 at 4:49










  • What do you mean by a random entry? By whom will the random entry be chosen?
    – Kevin Anderson
    Nov 11 at 4:52












  • I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.
    – JennaTools
    Nov 11 at 4:58










  • Use .keySet method on HashMap to obtain all the existing keys as a Set; use .toArray method on the key set to get an array of the keys. Generate a random number between zero and the size of the key array; get the key k at that index, use .remove(k) on the HashMap.
    – Kevin Anderson
    Nov 11 at 5:04


















By simply calling the remove(key) that will remove the element with that key.
– imprezzeb
Nov 11 at 4:49




By simply calling the remove(key) that will remove the element with that key.
– imprezzeb
Nov 11 at 4:49












What do you mean by a random entry? By whom will the random entry be chosen?
– Kevin Anderson
Nov 11 at 4:52






What do you mean by a random entry? By whom will the random entry be chosen?
– Kevin Anderson
Nov 11 at 4:52














I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.
– JennaTools
Nov 11 at 4:58




I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.
– JennaTools
Nov 11 at 4:58












Use .keySet method on HashMap to obtain all the existing keys as a Set; use .toArray method on the key set to get an array of the keys. Generate a random number between zero and the size of the key array; get the key k at that index, use .remove(k) on the HashMap.
– Kevin Anderson
Nov 11 at 5:04






Use .keySet method on HashMap to obtain all the existing keys as a Set; use .toArray method on the key set to get an array of the keys. Generate a random number between zero and the size of the key array; get the key k at that index, use .remove(k) on the HashMap.
– Kevin Anderson
Nov 11 at 5:04














3 Answers
3






active

oldest

votes

















up vote
0
down vote



accepted










The problem, as I understand it, is this: given a HashMap you want to




  1. Choose a key at random from among the the keys currently associated in the Map;

  2. Remove that association of that randomly chosen key from the map; and

  3. Return the value that had, until recently, been associated with that key


Here's an example of how to do this, along with some a little test/demonstration routine:



public class Main
{
private static <K, V> V removeRandomEntry(Map<K, V> map){
Set<K> keySet = map.keySet();
List<K> keyList = new ArrayList<>(keySet);
K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));
return map.remove(keyToRemove);
}

public static void main(String args){
Map<String, String> map = new HashMap<>();
for(int i = 0; i < 100; ++i)
map.put("Key" + i, "Value"+i);
int pass = 0;
while (!map.isEmpty())
System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));
}
}





share|improve this answer




























    up vote
    2
    down vote













    Maybe Map#computeIfPresent would work in your case. From its documentation:




    If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.



    If the remapping function returns null, the mapping is removed.




    var map = new HashMap<Integer, String>();

    map.put(1, "One");
    map.put(2, "Two");
    map.put(3, "Three");

    map.computeIfPresent(2, (k, v) -> {
    // `v` is equal to "Two"
    return null; // Returning `null` removes the entry from the map.
    });

    System.out.println(map);


    The above code outputs the following:



    {1=One, 3=Three}


    If you were to use a ConcurrentHashMap, then this would be an atomic operation.






    share|improve this answer




























      up vote
      0
      down vote













      I would do it like this:



      Hashmap<Integer, Object> example;
      int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
      example.getValue() //do something
      example.remove(new Integer(randomNum));





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














         

        draft saved


        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245918%2fjava-hashmap-how-to-simultaneously-get-and-then-remove-a-random-entry-from-a-h%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        0
        down vote



        accepted










        The problem, as I understand it, is this: given a HashMap you want to




        1. Choose a key at random from among the the keys currently associated in the Map;

        2. Remove that association of that randomly chosen key from the map; and

        3. Return the value that had, until recently, been associated with that key


        Here's an example of how to do this, along with some a little test/demonstration routine:



        public class Main
        {
        private static <K, V> V removeRandomEntry(Map<K, V> map){
        Set<K> keySet = map.keySet();
        List<K> keyList = new ArrayList<>(keySet);
        K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));
        return map.remove(keyToRemove);
        }

        public static void main(String args){
        Map<String, String> map = new HashMap<>();
        for(int i = 0; i < 100; ++i)
        map.put("Key" + i, "Value"+i);
        int pass = 0;
        while (!map.isEmpty())
        System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));
        }
        }





        share|improve this answer

























          up vote
          0
          down vote



          accepted










          The problem, as I understand it, is this: given a HashMap you want to




          1. Choose a key at random from among the the keys currently associated in the Map;

          2. Remove that association of that randomly chosen key from the map; and

          3. Return the value that had, until recently, been associated with that key


          Here's an example of how to do this, along with some a little test/demonstration routine:



          public class Main
          {
          private static <K, V> V removeRandomEntry(Map<K, V> map){
          Set<K> keySet = map.keySet();
          List<K> keyList = new ArrayList<>(keySet);
          K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));
          return map.remove(keyToRemove);
          }

          public static void main(String args){
          Map<String, String> map = new HashMap<>();
          for(int i = 0; i < 100; ++i)
          map.put("Key" + i, "Value"+i);
          int pass = 0;
          while (!map.isEmpty())
          System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));
          }
          }





          share|improve this answer























            up vote
            0
            down vote



            accepted







            up vote
            0
            down vote



            accepted






            The problem, as I understand it, is this: given a HashMap you want to




            1. Choose a key at random from among the the keys currently associated in the Map;

            2. Remove that association of that randomly chosen key from the map; and

            3. Return the value that had, until recently, been associated with that key


            Here's an example of how to do this, along with some a little test/demonstration routine:



            public class Main
            {
            private static <K, V> V removeRandomEntry(Map<K, V> map){
            Set<K> keySet = map.keySet();
            List<K> keyList = new ArrayList<>(keySet);
            K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));
            return map.remove(keyToRemove);
            }

            public static void main(String args){
            Map<String, String> map = new HashMap<>();
            for(int i = 0; i < 100; ++i)
            map.put("Key" + i, "Value"+i);
            int pass = 0;
            while (!map.isEmpty())
            System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));
            }
            }





            share|improve this answer












            The problem, as I understand it, is this: given a HashMap you want to




            1. Choose a key at random from among the the keys currently associated in the Map;

            2. Remove that association of that randomly chosen key from the map; and

            3. Return the value that had, until recently, been associated with that key


            Here's an example of how to do this, along with some a little test/demonstration routine:



            public class Main
            {
            private static <K, V> V removeRandomEntry(Map<K, V> map){
            Set<K> keySet = map.keySet();
            List<K> keyList = new ArrayList<>(keySet);
            K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));
            return map.remove(keyToRemove);
            }

            public static void main(String args){
            Map<String, String> map = new HashMap<>();
            for(int i = 0; i < 100; ++i)
            map.put("Key" + i, "Value"+i);
            int pass = 0;
            while (!map.isEmpty())
            System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));
            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 at 5:40









            Kevin Anderson

            2,7392617




            2,7392617
























                up vote
                2
                down vote













                Maybe Map#computeIfPresent would work in your case. From its documentation:




                If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.



                If the remapping function returns null, the mapping is removed.




                var map = new HashMap<Integer, String>();

                map.put(1, "One");
                map.put(2, "Two");
                map.put(3, "Three");

                map.computeIfPresent(2, (k, v) -> {
                // `v` is equal to "Two"
                return null; // Returning `null` removes the entry from the map.
                });

                System.out.println(map);


                The above code outputs the following:



                {1=One, 3=Three}


                If you were to use a ConcurrentHashMap, then this would be an atomic operation.






                share|improve this answer

























                  up vote
                  2
                  down vote













                  Maybe Map#computeIfPresent would work in your case. From its documentation:




                  If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.



                  If the remapping function returns null, the mapping is removed.




                  var map = new HashMap<Integer, String>();

                  map.put(1, "One");
                  map.put(2, "Two");
                  map.put(3, "Three");

                  map.computeIfPresent(2, (k, v) -> {
                  // `v` is equal to "Two"
                  return null; // Returning `null` removes the entry from the map.
                  });

                  System.out.println(map);


                  The above code outputs the following:



                  {1=One, 3=Three}


                  If you were to use a ConcurrentHashMap, then this would be an atomic operation.






                  share|improve this answer























                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    Maybe Map#computeIfPresent would work in your case. From its documentation:




                    If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.



                    If the remapping function returns null, the mapping is removed.




                    var map = new HashMap<Integer, String>();

                    map.put(1, "One");
                    map.put(2, "Two");
                    map.put(3, "Three");

                    map.computeIfPresent(2, (k, v) -> {
                    // `v` is equal to "Two"
                    return null; // Returning `null` removes the entry from the map.
                    });

                    System.out.println(map);


                    The above code outputs the following:



                    {1=One, 3=Three}


                    If you were to use a ConcurrentHashMap, then this would be an atomic operation.






                    share|improve this answer












                    Maybe Map#computeIfPresent would work in your case. From its documentation:




                    If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.



                    If the remapping function returns null, the mapping is removed.




                    var map = new HashMap<Integer, String>();

                    map.put(1, "One");
                    map.put(2, "Two");
                    map.put(3, "Three");

                    map.computeIfPresent(2, (k, v) -> {
                    // `v` is equal to "Two"
                    return null; // Returning `null` removes the entry from the map.
                    });

                    System.out.println(map);


                    The above code outputs the following:



                    {1=One, 3=Three}


                    If you were to use a ConcurrentHashMap, then this would be an atomic operation.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 at 4:48









                    Jacob G.

                    14.7k51961




                    14.7k51961






















                        up vote
                        0
                        down vote













                        I would do it like this:



                        Hashmap<Integer, Object> example;
                        int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
                        example.getValue() //do something
                        example.remove(new Integer(randomNum));





                        share|improve this answer



























                          up vote
                          0
                          down vote













                          I would do it like this:



                          Hashmap<Integer, Object> example;
                          int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
                          example.getValue() //do something
                          example.remove(new Integer(randomNum));





                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            I would do it like this:



                            Hashmap<Integer, Object> example;
                            int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
                            example.getValue() //do something
                            example.remove(new Integer(randomNum));





                            share|improve this answer














                            I would do it like this:



                            Hashmap<Integer, Object> example;
                            int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
                            example.getValue() //do something
                            example.remove(new Integer(randomNum));






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 11 at 5:56

























                            answered Nov 11 at 4:58









                            Yulo Vallejos

                            37




                            37






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245918%2fjava-hashmap-how-to-simultaneously-get-and-then-remove-a-random-entry-from-a-h%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                List item for chat from Array inside array React Native

                                Thiostrepton

                                Caerphilly