title: Can I get the key from SharedPreferences if a know the associated value?
body: <p>Is it possible to get the "key" value from a SharedPreferences file if I know the "value" value it is paired with?</p>
  
  <p>Let's say I've gone into the SharedPreferences file and, through a user action, have got the value "London, UK".</p>
  
  <p>Now I want to get the KEY associated with the value "London, UK" and then use that for my next step, is this possible?</p>
  
  <p>The code I use at the moment to getAll data from the SharedPerferences, sort it by value, populate an AlertDialog with this data, deal with a user choosing an option from the AlertDialog and then returning the value of that choice. I now need the KEY that's paired with the value.</p>
  
  <pre><code>public void openServerDialog() {
  
  
          final SharedPreferences myPrefs = this.getSharedPreferences("FileName", MODE_PRIVATE);
          TreeMap&lt;String, ?&gt; keys = new TreeMap&lt;String, Object&gt;(myPrefs.getAll());
          for (Map.Entry&lt;String, ?&gt; entry : keys.entrySet()) {
              Log.i("map values", entry.getKey());
              //some code
          }
  
  
        List&lt;Pair&lt;Object, String&gt;&gt; sortedByValue = new LinkedList&lt;Pair&lt;Object,String&gt;&gt;();
          for (Map.Entry&lt;String, ?&gt; entry : keys.entrySet()) {
              Pair&lt;Object, String&gt; e = new Pair&lt;Object, String&gt;(entry.getValue(), entry.getKey());
              sortedByValue.add(e);
          }
  
       // Pair doesn't have a comparator, so you're going to need to write one.
          Collections.sort(sortedByValue, new Comparator&lt;Pair&lt;Object, String&gt;&gt;() {
              public int compare(Pair&lt;Object, String&gt; lhs, Pair&lt;Object, String&gt; rhs) {
  
                  String sls = String.valueOf(lhs.first);
                  String srs = String.valueOf(rhs.first);
                  int res = sls.compareTo(srs);
                  // Sort on value first, key second
                  return res == 0 ? lhs.second.compareTo(rhs.second) : res;
              }
          });
  
          for (Pair&lt;Object, String&gt; pair : sortedByValue) {
              Log.i("map values", pair.first + "/" + pair.second);
          }
  
  
        Collection&lt;?&gt; stringArrayList = keys.values();
        final CharSequence[] prefsCharSequence = stringArrayList.toArray(new CharSequence[stringArrayList.size()]);
  
          new AlertDialog.Builder(this)   
          .setTitle(R.string.server_title)
          .setItems(prefsCharSequence, 
          new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialoginterface, int i) {
  
                  setServer(prefsCharSequence[i]);   
  
              }
          })
          .show();
      }
  </code></pre>