O(1) method of getting K using V with a java hashmap? [duplicate]











up vote
1
down vote

favorite
1













This question already has an answer here:




  • Bidirectional Map

    6 answers




In Java 8 is there an O(1) method of getting the K by using V for a hashmap? Would I have to use two hashmaps(KV and VK) and if so would that defeat the purpose of having O(1)?



For context, I am trying to find the most efficient way of getting (String userName, Integer userIdentifier) using either value or key.










share|improve this question









New contributor




TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











marked as duplicate by Mark Rotteveel java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 9 at 10:26


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • There is no method for O(1) lookup via value. You could use another HashMap like what you mentioned, provided the values are unique.
    – Jai
    Nov 8 at 8:10










  • Ah ok thanks, the values are unique. No user can have the same userIdentifier and vice versa.
    – TangoFoxtrot
    Nov 8 at 8:21






  • 1




    There is a BiMap in Guava, both sides can be used as key as you require, KV & VK
    – buræquete
    Nov 8 at 8:22






  • 1




    The key by definition is the data you use to lookup, and the value is the data looked up.
    – Peter Lawrey
    Nov 8 at 9:59















up vote
1
down vote

favorite
1













This question already has an answer here:




  • Bidirectional Map

    6 answers




In Java 8 is there an O(1) method of getting the K by using V for a hashmap? Would I have to use two hashmaps(KV and VK) and if so would that defeat the purpose of having O(1)?



For context, I am trying to find the most efficient way of getting (String userName, Integer userIdentifier) using either value or key.










share|improve this question









New contributor




TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











marked as duplicate by Mark Rotteveel java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 9 at 10:26


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • There is no method for O(1) lookup via value. You could use another HashMap like what you mentioned, provided the values are unique.
    – Jai
    Nov 8 at 8:10










  • Ah ok thanks, the values are unique. No user can have the same userIdentifier and vice versa.
    – TangoFoxtrot
    Nov 8 at 8:21






  • 1




    There is a BiMap in Guava, both sides can be used as key as you require, KV & VK
    – buræquete
    Nov 8 at 8:22






  • 1




    The key by definition is the data you use to lookup, and the value is the data looked up.
    – Peter Lawrey
    Nov 8 at 9:59













up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1






This question already has an answer here:




  • Bidirectional Map

    6 answers




In Java 8 is there an O(1) method of getting the K by using V for a hashmap? Would I have to use two hashmaps(KV and VK) and if so would that defeat the purpose of having O(1)?



For context, I am trying to find the most efficient way of getting (String userName, Integer userIdentifier) using either value or key.










share|improve this question









New contributor




TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












This question already has an answer here:




  • Bidirectional Map

    6 answers




In Java 8 is there an O(1) method of getting the K by using V for a hashmap? Would I have to use two hashmaps(KV and VK) and if so would that defeat the purpose of having O(1)?



For context, I am trying to find the most efficient way of getting (String userName, Integer userIdentifier) using either value or key.





This question already has an answer here:




  • Bidirectional Map

    6 answers








java performance dictionary hashmap






share|improve this question









New contributor




TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 8 at 8:23









Mureinik

174k21123191




174k21123191






New contributor




TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 8 at 8:08









TangoFoxtrot

43




43




New contributor




TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






TangoFoxtrot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




marked as duplicate by Mark Rotteveel java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 9 at 10:26


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Mark Rotteveel java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 9 at 10:26


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • There is no method for O(1) lookup via value. You could use another HashMap like what you mentioned, provided the values are unique.
    – Jai
    Nov 8 at 8:10










  • Ah ok thanks, the values are unique. No user can have the same userIdentifier and vice versa.
    – TangoFoxtrot
    Nov 8 at 8:21






  • 1




    There is a BiMap in Guava, both sides can be used as key as you require, KV & VK
    – buræquete
    Nov 8 at 8:22






  • 1




    The key by definition is the data you use to lookup, and the value is the data looked up.
    – Peter Lawrey
    Nov 8 at 9:59


















  • There is no method for O(1) lookup via value. You could use another HashMap like what you mentioned, provided the values are unique.
    – Jai
    Nov 8 at 8:10










  • Ah ok thanks, the values are unique. No user can have the same userIdentifier and vice versa.
    – TangoFoxtrot
    Nov 8 at 8:21






  • 1




    There is a BiMap in Guava, both sides can be used as key as you require, KV & VK
    – buræquete
    Nov 8 at 8:22






  • 1




    The key by definition is the data you use to lookup, and the value is the data looked up.
    – Peter Lawrey
    Nov 8 at 9:59
















There is no method for O(1) lookup via value. You could use another HashMap like what you mentioned, provided the values are unique.
– Jai
Nov 8 at 8:10




There is no method for O(1) lookup via value. You could use another HashMap like what you mentioned, provided the values are unique.
– Jai
Nov 8 at 8:10












Ah ok thanks, the values are unique. No user can have the same userIdentifier and vice versa.
– TangoFoxtrot
Nov 8 at 8:21




Ah ok thanks, the values are unique. No user can have the same userIdentifier and vice versa.
– TangoFoxtrot
Nov 8 at 8:21




1




1




There is a BiMap in Guava, both sides can be used as key as you require, KV & VK
– buræquete
Nov 8 at 8:22




There is a BiMap in Guava, both sides can be used as key as you require, KV & VK
– buræquete
Nov 8 at 8:22




1




1




The key by definition is the data you use to lookup, and the value is the data looked up.
– Peter Lawrey
Nov 8 at 9:59




The key by definition is the data you use to lookup, and the value is the data looked up.
– Peter Lawrey
Nov 8 at 9:59












3 Answers
3






active

oldest

votes

















up vote
5
down vote



accepted










As a general note - there's a hidden assumption here that the values are also unique. Otherwise, you won't be able to retrieve a single key by a value, but a list of keys, although even if you take that into consideration it won't change the answer much. Additionally, with your usecase of userName and userId, this may be a moot point altogether.



As you alluded, a simple HashMap won't be enough - that would mean you'd need to iterate over the entries to find an entry with a specific key, which would be an O(n) operation.



Using two HashMaps (name to id and id to name) is a good approach. While this would mean you'd have to perform two operations instead of one each time you add/remove/modify a user, it won't affect the order of magnitude (since you're still performing a constant number of constant-time operations), and you'll retain the O(1) insertion time.

This is in fact a pretty common approach, and if you can introduce third-party libraries to your project, there are pretty solid implementations of this concept out there, like Apache Commons Collections' DualHashBidiMap.






share|improve this answer




























    up vote
    3
    down vote













    Maps are meant for searching by key, so you won't get O(1) lookup by value, unless you use a second map.



    What serves your use case is a BiMap avaliable from Google Guava



    BiMap<String, Integer> nameidmap = HashBiMap.create();
    Integer id = nameidmap.get("name");
    String name = nameidmap.inverse().get(12345);


    Internally Guava also maintains two hash tables, but it does the heavy lifting of keeping the two maps in sync. You can find full Javadoc for Bimap here.






    share|improve this answer




























      up vote
      2
      down vote













      If you want to use only single hashmap, you can do




      map.put(key, value) and then map.put(value, key)




      Assuming values are unique and also not equal to any key






      share|improve this answer




























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        5
        down vote



        accepted










        As a general note - there's a hidden assumption here that the values are also unique. Otherwise, you won't be able to retrieve a single key by a value, but a list of keys, although even if you take that into consideration it won't change the answer much. Additionally, with your usecase of userName and userId, this may be a moot point altogether.



        As you alluded, a simple HashMap won't be enough - that would mean you'd need to iterate over the entries to find an entry with a specific key, which would be an O(n) operation.



        Using two HashMaps (name to id and id to name) is a good approach. While this would mean you'd have to perform two operations instead of one each time you add/remove/modify a user, it won't affect the order of magnitude (since you're still performing a constant number of constant-time operations), and you'll retain the O(1) insertion time.

        This is in fact a pretty common approach, and if you can introduce third-party libraries to your project, there are pretty solid implementations of this concept out there, like Apache Commons Collections' DualHashBidiMap.






        share|improve this answer

























          up vote
          5
          down vote



          accepted










          As a general note - there's a hidden assumption here that the values are also unique. Otherwise, you won't be able to retrieve a single key by a value, but a list of keys, although even if you take that into consideration it won't change the answer much. Additionally, with your usecase of userName and userId, this may be a moot point altogether.



          As you alluded, a simple HashMap won't be enough - that would mean you'd need to iterate over the entries to find an entry with a specific key, which would be an O(n) operation.



          Using two HashMaps (name to id and id to name) is a good approach. While this would mean you'd have to perform two operations instead of one each time you add/remove/modify a user, it won't affect the order of magnitude (since you're still performing a constant number of constant-time operations), and you'll retain the O(1) insertion time.

          This is in fact a pretty common approach, and if you can introduce third-party libraries to your project, there are pretty solid implementations of this concept out there, like Apache Commons Collections' DualHashBidiMap.






          share|improve this answer























            up vote
            5
            down vote



            accepted







            up vote
            5
            down vote



            accepted






            As a general note - there's a hidden assumption here that the values are also unique. Otherwise, you won't be able to retrieve a single key by a value, but a list of keys, although even if you take that into consideration it won't change the answer much. Additionally, with your usecase of userName and userId, this may be a moot point altogether.



            As you alluded, a simple HashMap won't be enough - that would mean you'd need to iterate over the entries to find an entry with a specific key, which would be an O(n) operation.



            Using two HashMaps (name to id and id to name) is a good approach. While this would mean you'd have to perform two operations instead of one each time you add/remove/modify a user, it won't affect the order of magnitude (since you're still performing a constant number of constant-time operations), and you'll retain the O(1) insertion time.

            This is in fact a pretty common approach, and if you can introduce third-party libraries to your project, there are pretty solid implementations of this concept out there, like Apache Commons Collections' DualHashBidiMap.






            share|improve this answer












            As a general note - there's a hidden assumption here that the values are also unique. Otherwise, you won't be able to retrieve a single key by a value, but a list of keys, although even if you take that into consideration it won't change the answer much. Additionally, with your usecase of userName and userId, this may be a moot point altogether.



            As you alluded, a simple HashMap won't be enough - that would mean you'd need to iterate over the entries to find an entry with a specific key, which would be an O(n) operation.



            Using two HashMaps (name to id and id to name) is a good approach. While this would mean you'd have to perform two operations instead of one each time you add/remove/modify a user, it won't affect the order of magnitude (since you're still performing a constant number of constant-time operations), and you'll retain the O(1) insertion time.

            This is in fact a pretty common approach, and if you can introduce third-party libraries to your project, there are pretty solid implementations of this concept out there, like Apache Commons Collections' DualHashBidiMap.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 8 at 8:19









            Mureinik

            174k21123191




            174k21123191
























                up vote
                3
                down vote













                Maps are meant for searching by key, so you won't get O(1) lookup by value, unless you use a second map.



                What serves your use case is a BiMap avaliable from Google Guava



                BiMap<String, Integer> nameidmap = HashBiMap.create();
                Integer id = nameidmap.get("name");
                String name = nameidmap.inverse().get(12345);


                Internally Guava also maintains two hash tables, but it does the heavy lifting of keeping the two maps in sync. You can find full Javadoc for Bimap here.






                share|improve this answer

























                  up vote
                  3
                  down vote













                  Maps are meant for searching by key, so you won't get O(1) lookup by value, unless you use a second map.



                  What serves your use case is a BiMap avaliable from Google Guava



                  BiMap<String, Integer> nameidmap = HashBiMap.create();
                  Integer id = nameidmap.get("name");
                  String name = nameidmap.inverse().get(12345);


                  Internally Guava also maintains two hash tables, but it does the heavy lifting of keeping the two maps in sync. You can find full Javadoc for Bimap here.






                  share|improve this answer























                    up vote
                    3
                    down vote










                    up vote
                    3
                    down vote









                    Maps are meant for searching by key, so you won't get O(1) lookup by value, unless you use a second map.



                    What serves your use case is a BiMap avaliable from Google Guava



                    BiMap<String, Integer> nameidmap = HashBiMap.create();
                    Integer id = nameidmap.get("name");
                    String name = nameidmap.inverse().get(12345);


                    Internally Guava also maintains two hash tables, but it does the heavy lifting of keeping the two maps in sync. You can find full Javadoc for Bimap here.






                    share|improve this answer












                    Maps are meant for searching by key, so you won't get O(1) lookup by value, unless you use a second map.



                    What serves your use case is a BiMap avaliable from Google Guava



                    BiMap<String, Integer> nameidmap = HashBiMap.create();
                    Integer id = nameidmap.get("name");
                    String name = nameidmap.inverse().get(12345);


                    Internally Guava also maintains two hash tables, but it does the heavy lifting of keeping the two maps in sync. You can find full Javadoc for Bimap here.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 8 at 8:22









                    Siddhesh Rane

                    10924




                    10924






















                        up vote
                        2
                        down vote













                        If you want to use only single hashmap, you can do




                        map.put(key, value) and then map.put(value, key)




                        Assuming values are unique and also not equal to any key






                        share|improve this answer

























                          up vote
                          2
                          down vote













                          If you want to use only single hashmap, you can do




                          map.put(key, value) and then map.put(value, key)




                          Assuming values are unique and also not equal to any key






                          share|improve this answer























                            up vote
                            2
                            down vote










                            up vote
                            2
                            down vote









                            If you want to use only single hashmap, you can do




                            map.put(key, value) and then map.put(value, key)




                            Assuming values are unique and also not equal to any key






                            share|improve this answer












                            If you want to use only single hashmap, you can do




                            map.put(key, value) and then map.put(value, key)




                            Assuming values are unique and also not equal to any key







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 8 at 9:23









                            Laxmikant

                            583312




                            583312















                                Popular posts from this blog

                                Schultheiß

                                Verwaltungsgliederung Dänemarks

                                Liste der Kulturdenkmale in Wilsdruff