Java Hashmap: How to get key from value?

前端 未结 30 2371
忘掉有多难
忘掉有多难 2020-11-22 02:14

If I have the value \"foo\", and a HashMap ftw for which ftw.containsValue(\"foo\") returns true, how can I

30条回答
  •  感动是毒
    2020-11-22 03:04

    1. If you want to get key from value, its best to use bidimap (bi-directional maps) , you can get key from value in O(1) time.

      But, the drawback with this is you can only use unique keyset and valueset.

    2. There is a data structure called Table in java, which is nothing but map of maps like

      Table< A, B , C > == map < A , map < B, C > >

      Here you can get map by querying T.row(a);, and you can also get map by querying T.column(b);

    In your special case, insert C as some constant.

    So, it like < a1, b1, 1 > < a2, b2 , 1 > , ...

    So, if you find via T.row(a1) ---> returns map of --> get keyset this returned map.

    If you need to find key value then, T.column(b2) --> returns map of --> get keyset of returned map.

    Advantages over the previous case :

    1. Can use multiple values.
    2. More efficient when using large data sets.

提交回复
热议问题