Home > Java > javaTutorial > body text

Java HashMap code example to check key through value

高洛峰
Release: 2017-01-19 10:14:52
Original
2003 people have browsed it

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;
  }
}
Copy after login

The results are as follows:

1
2
3
4
5
Copy after login


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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template