Home  >  Article  >  Java  >  Java HashMap code example to check key through value

Java HashMap code example to check key through value

高洛峰
高洛峰Original
2017-01-19 10:14:522000browse

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapValueGetKey {
  public static void main(String[] args) {
    Map map = new HashMap<>();
    map.put(1,"A");
    map.put(2,"A");
    map.put(3,"A");
    map.put(4,"A");
    map.put(5,"A");

    String value = "A";
    ArrayList arr = valueGetKey(map, value);
    if(!arr.isEmpty()) {
      for(int i=0; i<arr.size(); i++) {
        System.out.println(arr.get(i));
      }
    }

  }
  private static ArrayList valueGetKey(Map map,String value) {
    Set set = map.entrySet();
    ArrayList arr = new ArrayList<>();
    Iterator it = set.iterator();
    while(it.hasNext()) {
      Map.Entry entry = (Map.Entry)it.next();
      if(entry.getValue().equals(value)) {
        int s = (int)entry.getKey();
        arr.add(s);
      }
    }
    return arr;
  }
}

The results are as follows:

1
2
3
4
5


For more code examples of java HashMap checking key through value, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn