1

Basically, I've the following code:

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "test");
map.put(2, "test2");
// I can get the string using this:
String str = map.get("test2");
// but how do I get the index ('key') of "test2"?

The code is pretty much self explanatory. How do I get the '2'? Is it essential to use a loop?

  • The values of a map are not distinct, which means you can get multiple values matching more keys, therefore you are looking for a `List` of keys. List keys = map.entrySet().stream() .filter(e -> "Test2".equals(e.getValue())) .map(Entry::getKey) .collect(Collectors.toList()); – Nikolas Charalambidis Dec 16 '19 at 09:28

2 Answers2

1

As an alternative to using a loop, you can use Streams to locate the key matching a given value:

map.entrySet()
   .stream() // build a Stream<Map.Entry<Integer,String> of all the map entries
   .filter(e -> e.getValue().equals("test2")) // locate entries having the required value
   .map(Map.Entry::getKey) // map to the corresponding key
   .findFirst() // get the first match (there may be multiple matches)
   .orElse(null); // default value in case of no match
Eran
  • 387,369
  • 54
  • 702
  • 768
  • You could use .keySet() instead of .entrySet() and .map(Map.Entry::getKey) – Glavatar Dec 16 '19 at 09:27
  • 1
    @Glavatar if I use `keySet()` I have to call `map.get()` is order to check that the value matches the required value. – Eran Dec 16 '19 at 09:28
  • @glavatar but if he uses keySet, you'd only have the keys. But you need to work on the entries, because the entry's value is what to search by ("test2") and the key is what should be determined – Alexander Dec 16 '19 at 09:29
0

You can iterate over the map's entry and check for the key against matching value.

    int key = 0;
    for(Entry<Integer, String> entry:map.entrySet()) {
        if(entry.getValue().equals("test2")) {
            key=entry.getKey();
            break;
        }
    }
    System.out.println(key);

    // Using stream
    Optional<Entry<Integer, String>> element = map.entrySet().stream().filter(elem->elem.getValue().equals("test2")).findFirst();
    if(element.isPresent()) {
        System.out.println(element.get().getKey());
    }
manikant gautam
  • 3,521
  • 1
  • 17
  • 27