How do I find the value of an unknown key in my HashMap and convert it into an int?












0














Doesnt really need much of an explanation, just wondering what would be the best and efficient way to do that. The HashMap has only one Key left, (checked with map.size() == 1), however the Key is unknown. The HashMap is <Integer, Integer>.
Thanks a lot to everyone trying to help!










share|improve this question




















  • 1




    You can use Map#keySet() to obtain a set of keys. The rest should be self explanatory. You could also use Map#entrySet(), and iterate over these entries. An entry is an object that contains a key and a value. For example, for (Entry<Integer, Integer> entry : map.entrySet()) { print(entry.getKey() + entry.getValue(); }
    – PhaseRush
    Nov 23 '18 at 20:09


















0














Doesnt really need much of an explanation, just wondering what would be the best and efficient way to do that. The HashMap has only one Key left, (checked with map.size() == 1), however the Key is unknown. The HashMap is <Integer, Integer>.
Thanks a lot to everyone trying to help!










share|improve this question




















  • 1




    You can use Map#keySet() to obtain a set of keys. The rest should be self explanatory. You could also use Map#entrySet(), and iterate over these entries. An entry is an object that contains a key and a value. For example, for (Entry<Integer, Integer> entry : map.entrySet()) { print(entry.getKey() + entry.getValue(); }
    – PhaseRush
    Nov 23 '18 at 20:09
















0












0








0







Doesnt really need much of an explanation, just wondering what would be the best and efficient way to do that. The HashMap has only one Key left, (checked with map.size() == 1), however the Key is unknown. The HashMap is <Integer, Integer>.
Thanks a lot to everyone trying to help!










share|improve this question















Doesnt really need much of an explanation, just wondering what would be the best and efficient way to do that. The HashMap has only one Key left, (checked with map.size() == 1), however the Key is unknown. The HashMap is <Integer, Integer>.
Thanks a lot to everyone trying to help!







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 20:08









JB Nizet

535k52862995




535k52862995










asked Nov 23 '18 at 20:06









FABULATORFABULATOR

33




33








  • 1




    You can use Map#keySet() to obtain a set of keys. The rest should be self explanatory. You could also use Map#entrySet(), and iterate over these entries. An entry is an object that contains a key and a value. For example, for (Entry<Integer, Integer> entry : map.entrySet()) { print(entry.getKey() + entry.getValue(); }
    – PhaseRush
    Nov 23 '18 at 20:09
















  • 1




    You can use Map#keySet() to obtain a set of keys. The rest should be self explanatory. You could also use Map#entrySet(), and iterate over these entries. An entry is an object that contains a key and a value. For example, for (Entry<Integer, Integer> entry : map.entrySet()) { print(entry.getKey() + entry.getValue(); }
    – PhaseRush
    Nov 23 '18 at 20:09










1




1




You can use Map#keySet() to obtain a set of keys. The rest should be self explanatory. You could also use Map#entrySet(), and iterate over these entries. An entry is an object that contains a key and a value. For example, for (Entry<Integer, Integer> entry : map.entrySet()) { print(entry.getKey() + entry.getValue(); }
– PhaseRush
Nov 23 '18 at 20:09






You can use Map#keySet() to obtain a set of keys. The rest should be self explanatory. You could also use Map#entrySet(), and iterate over these entries. An entry is an object that contains a key and a value. For example, for (Entry<Integer, Integer> entry : map.entrySet()) { print(entry.getKey() + entry.getValue(); }
– PhaseRush
Nov 23 '18 at 20:09














2 Answers
2






active

oldest

votes


















2














As .keySet() and .entrySet() returns Set you can't direct use a get operation like with List





  1. Through Stream you can :



    int unknowKey = map.keySet().stream()
    .findAny()
    .orElseThrow(IllegalArgumentException::new);



  2. Or, with Iterator :



    int unknowKey = map.keySet().iterator().next();





In term of efficiency, iterator is really superior:



Benchmark         Mode   Cnt    Score    Error   Units
MyBench.iterator avgt 5 10,663 ± 0,175 ns/op
MyBench.stream avgt 5 47,960 ± 4,819 ns/op





share|improve this answer























  • Nice analysis :) ... I think conversion to a stream takes time maybe
    – mettleap
    Nov 23 '18 at 20:39



















3














Use the keySet method to get the key in a set and then iterate through the set to get the key, like so,



    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(5, 1); // some map with only one key-value pair

int a = map.keySet().iterator().next(); // obtain keyset, get iterator and get the next element (since you know map size is 1)

System.out.println(a);





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',
    autoActivateHeartbeat: false,
    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%2f53452404%2fhow-do-i-find-the-value-of-an-unknown-key-in-my-hashmap-and-convert-it-into-an-i%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    As .keySet() and .entrySet() returns Set you can't direct use a get operation like with List





    1. Through Stream you can :



      int unknowKey = map.keySet().stream()
      .findAny()
      .orElseThrow(IllegalArgumentException::new);



    2. Or, with Iterator :



      int unknowKey = map.keySet().iterator().next();





    In term of efficiency, iterator is really superior:



    Benchmark         Mode   Cnt    Score    Error   Units
    MyBench.iterator avgt 5 10,663 ± 0,175 ns/op
    MyBench.stream avgt 5 47,960 ± 4,819 ns/op





    share|improve this answer























    • Nice analysis :) ... I think conversion to a stream takes time maybe
      – mettleap
      Nov 23 '18 at 20:39
















    2














    As .keySet() and .entrySet() returns Set you can't direct use a get operation like with List





    1. Through Stream you can :



      int unknowKey = map.keySet().stream()
      .findAny()
      .orElseThrow(IllegalArgumentException::new);



    2. Or, with Iterator :



      int unknowKey = map.keySet().iterator().next();





    In term of efficiency, iterator is really superior:



    Benchmark         Mode   Cnt    Score    Error   Units
    MyBench.iterator avgt 5 10,663 ± 0,175 ns/op
    MyBench.stream avgt 5 47,960 ± 4,819 ns/op





    share|improve this answer























    • Nice analysis :) ... I think conversion to a stream takes time maybe
      – mettleap
      Nov 23 '18 at 20:39














    2












    2








    2






    As .keySet() and .entrySet() returns Set you can't direct use a get operation like with List





    1. Through Stream you can :



      int unknowKey = map.keySet().stream()
      .findAny()
      .orElseThrow(IllegalArgumentException::new);



    2. Or, with Iterator :



      int unknowKey = map.keySet().iterator().next();





    In term of efficiency, iterator is really superior:



    Benchmark         Mode   Cnt    Score    Error   Units
    MyBench.iterator avgt 5 10,663 ± 0,175 ns/op
    MyBench.stream avgt 5 47,960 ± 4,819 ns/op





    share|improve this answer














    As .keySet() and .entrySet() returns Set you can't direct use a get operation like with List





    1. Through Stream you can :



      int unknowKey = map.keySet().stream()
      .findAny()
      .orElseThrow(IllegalArgumentException::new);



    2. Or, with Iterator :



      int unknowKey = map.keySet().iterator().next();





    In term of efficiency, iterator is really superior:



    Benchmark         Mode   Cnt    Score    Error   Units
    MyBench.iterator avgt 5 10,663 ± 0,175 ns/op
    MyBench.stream avgt 5 47,960 ± 4,819 ns/op






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 23 '18 at 20:21

























    answered Nov 23 '18 at 20:13









    azroazro

    10.5k41438




    10.5k41438












    • Nice analysis :) ... I think conversion to a stream takes time maybe
      – mettleap
      Nov 23 '18 at 20:39


















    • Nice analysis :) ... I think conversion to a stream takes time maybe
      – mettleap
      Nov 23 '18 at 20:39
















    Nice analysis :) ... I think conversion to a stream takes time maybe
    – mettleap
    Nov 23 '18 at 20:39




    Nice analysis :) ... I think conversion to a stream takes time maybe
    – mettleap
    Nov 23 '18 at 20:39













    3














    Use the keySet method to get the key in a set and then iterate through the set to get the key, like so,



        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(5, 1); // some map with only one key-value pair

    int a = map.keySet().iterator().next(); // obtain keyset, get iterator and get the next element (since you know map size is 1)

    System.out.println(a);





    share|improve this answer


























      3














      Use the keySet method to get the key in a set and then iterate through the set to get the key, like so,



          HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
      map.put(5, 1); // some map with only one key-value pair

      int a = map.keySet().iterator().next(); // obtain keyset, get iterator and get the next element (since you know map size is 1)

      System.out.println(a);





      share|improve this answer
























        3












        3








        3






        Use the keySet method to get the key in a set and then iterate through the set to get the key, like so,



            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(5, 1); // some map with only one key-value pair

        int a = map.keySet().iterator().next(); // obtain keyset, get iterator and get the next element (since you know map size is 1)

        System.out.println(a);





        share|improve this answer












        Use the keySet method to get the key in a set and then iterate through the set to get the key, like so,



            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(5, 1); // some map with only one key-value pair

        int a = map.keySet().iterator().next(); // obtain keyset, get iterator and get the next element (since you know map size is 1)

        System.out.println(a);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 20:11









        mettleapmettleap

        1,080216




        1,080216






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53452404%2fhow-do-i-find-the-value-of-an-unknown-key-in-my-hashmap-and-convert-it-into-an-i%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

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks