Map TreeMap get key by value Java Android example

Get key by value from Map Java Android example

MainClass.java

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
 
public class MainClass {
	public static void main(String[] arg) {
 
		// english;germany dictionary
		String[] arrayOfString = { "one;eine", "two;zwei", "two sets of;zwei"
				, "three;drei", "four;vier" };
 
		Map<String, String> map = new TreeMap<String, String>();
 
		for (String s : arrayOfString) {
			String[] array = s.split(";");
			String sKey = "", sValue = "";
			if (array.length > 1) {
				sKey = array[0];
				sValue = array[1];
				map.put(sKey, sValue);
			}
		}
 
		if (map.containsValue("zwei")) {
			Set<String> references = getKeysByValue(map, "zwei");
			 Iterator<String> it = references.iterator();
			    while (it.hasNext()) {
			      String key = (String) it.next();
			      String value = map.get(key);
			      System.out.println(key + " = " + value);
			    }
		}
 
	}
 
	public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
		Set<T> keys = new HashSet<T>();
		for (Entry<T, E> entry : map.entrySet()) {
			if (entry.getValue().equals(value)) {
				keys.add(entry.getKey());
			}
		}
		return keys;
	}
}
/*
two = zwei
two sets of = zwei
 */
This entry was posted in Android Examples Code, Array,List,Collections and tagged , , , , , . Bookmark the permalink.


Comments are closed.

5,950 views