',', '로 할 경우 이 값은 " foo" HashMap< String>; 프트와 (foo" ";) '를' 프트웨인콩탱스발루 되돌려줍니다 해당 키 'true', '어떻게 해야 할까요? 루프 이스마프 통해 하나요? 그렇게 할 수 있는 최선의 방법은 무엇입니까?
이 경우 데이터 구조 및 값프로필 반복할 합니다 매핑에서는 n:1 키 사이의 모든 항목을 선택하고 적절한 키:
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 (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
자바 가상 머신 (jvm) 에 8:
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
return map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
또한 사용자, 구아바 비마프 유용할 수 있습니다. 예를 들면 다음과 같습니다.
BiMap<Token, Character> tokenToChar =
ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);
선택하여 사용할 경우 커먼즈 컬렉션 라이브러리란 모음 대신 표준 Java API 를 손쉽게 얻을 수 있습니다.
이 라이브러리는 모음 비디마프 인터페이스를 사용할 수 있는 양방향 매핑해야 매핑하려면 키 값 (일반 매핑하므로 등), 그리고 매핑하려면 핵심 가치가 있으므로 양방향으로 조회를 수행할 수 있습니다. 키 값을 받기 위해 의해 지원되며, [제키 () 메서드를] [3].
하지만, 여러 개의 값을 가질 수 없는 양방향 없다 단서 조항 때문에, 데이터의 집합이 아니라면 매핑하므로 매핑됨 키 키 사이의 및 값프로필 1:1 매핑이라는 비디마프스 사용할 수 없습니다.
스케쳐내 Java API 를 이용할 수 있는 컬렉션을 1:1 관계를 유지할 수 있도록 할 때 키 값을 삽입 및 값프로필 꽂으십시오 매핑해야. 이게 말처럼 쉬운 일은 아니다.
한 번 확인할 수 있습니다, [엔트리스트 () 메서드를] [4] 를 사용하여 입수합니다 항목 (매핑이라는) 의 집합을 매핑해야. 설정 후에는 그 유형은 취득됩니다 마피렌트리, [저장된 값] [6] 아니했으니 반복할 항목을 비교 및 입수합니다 걱정했던것 [해당 키가] [7].
지원할 수 있는 양방향 일반 매핑하므로 찾아볼 수 있다. 구글 구아바 과 일반적인 모음 세이스트 라이브러리보다는 (후자는 아파치 프로젝트가 아닙니다). 에스코 덕분에 대한 지적이 누각되었습니다 일반 지원하기 위해 아파치 커먼즈 컬렉션. 설치하고 관리할 수 있는 일반 컬렉션을 사용하여 더 코드.
[3]: # getKey% http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/bidimap.html 28java.lang.object% 29 [4]: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html # 엔트리스트 ()
[6]: https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html # 제바루이 () [7]: https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html # 제키 ()
public class NewClass1 {
public static void main(String[] args) {
Map<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(10, "a");
testMap.put(20, "b");
testMap.put(30, "c");
testMap.put(40, "d");
for (Entry<Integer, String> entry : testMap.entrySet()) {
if (entry.getValue().equals("c")) {
System.out.println(entry.getKey());
}
}
}
}
정말 좋은 않을 경우 위의 방법을 이스마프 컸다. 이스마프 고유 키를 포함할 경우 고유 값 매핑에서는 하나 더 들어 있는 주요 값에서 매핑에서는 이스마프 유지할 수 있습니다.
즉 두 개의 이스마프스 유지할 수 있습니다.
1. Key to value
2. Value to key
이 경우 두 번째 주요 afaq 이스마프 사용할 수 있습니다.
내 생각엔 선택이 가능합니다
[1]: com/google/common/collect/bimap.html http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?
키 값을 모두 삽입하십시오 페어당 보색으로 를 맵 구조를 줄 수 있다.
map.put("theKey", "theValue");
map.put("theValue", "theKey");
마피제 사용하여 (theValue" ";) 그러면 theKey" 복귀하십시오 ";).
자신의 이름으로 구축현 매핑해야 장식하는
class MyMap<K,V> extends HashMap<K, V>{
Map<V,K> reverseMap = new HashMap<V,K>();
@Override
public V put(K key, V value) {
// TODO Auto-generated method stub
reverseMap.put(value, key);
return super.put(key, value);
}
public K getKey(V value){
return reverseMap.get(value);
}
}
내 생각에 이것은 최상의 솔루션, 원래 주소: Java2s
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] argv) {
Map<String, String> map = new HashMap<String, String>();
map.put("1","one");
map.put("2","two");
map.put("3","three");
map.put("4","four");
System.out.println(getKeyFromValue(map,"three"));
}
// hm is the map you are trying to get value from it
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
}
쉬운 사용: 모든 데이터를 가지고 있고, Automobile" 이스마프 배치할 경우, 이스마프 에 해당하는 주요 항목 = " 있도록 찾고 있다. 즉 좋은 솔루션.
getKeyFromValue(hashMap, item);
System.out.println("getKeyFromValue(hashMap, item): "+getKeyFromValue(hashMap, item));
Iterator<Map.Entry<String,String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> entry = iter.next();
if (entry.getValue().equals(value_you_look_for)) {
String key_you_look_for = entry.getKey();
}
}
안드로이드 개발 API 를 겨냥한 <. # 39 비탈리아 표도렌코 일대일 관계 때문에 ' (19), t, t # 39 doesn& 솔루션이므로 작동합니까 로비치s. 퀄스' isn& 모색하십시오. # 39 의 here& 간단한 대체.
public <K, V> K getKeyByValue(Map<K, V> map, V value) {
for (Map.Entry<K, V> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
아래 사용할 수 있습니다.
public class HashmapKeyExist {
public static void main(String[] args) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("1", "Bala");
hmap.put("2", "Test");
Boolean cantain = hmap.containsValue("Bala");
if(hmap.containsKey("2") && hmap.containsValue("Test"))
{
System.out.println("Yes");
}
if(cantain == true)
{
System.out.println("Yes");
}
Set setkeys = hmap.keySet();
Iterator it = setkeys.iterator();
while(it.hasNext())
{
String key = (String) it.next();
if (hmap.get(key).equals("Bala"))
{
System.out.println(key);
}
}
}
}
그래, 네가 한 일을 반복할 이스마프 따라 다양한 질문에 대한 답변을 통해 구현할 수 흐름선 뭐한테 제안하세요. # 39 를 엔트리스트 I& 손보는 아닌, 그냥 크리스트 내려받습니다; d (), 세트, 있는 그대로 반복할 (first) 키 값을 얻을 수 있는 일치하는 드립니다. 모든 시동키는 일치하는 값을 하는 경우, 분명히 전부 수행해야 합니다.
이 같은 조치를 취할 수 있도록 하는 방법을 이미 요나스 제안됩니다 지정값이 콩탱스발루 지정값이 테스트하는 척 모두 함께 할 때마다 그냥 건너띄기 이터레이션은 (아님 컴파일러에서 이미 잘 아는 중복용으로 없음).
또 다른 대답을 상대치 경우 매핑해야 역동기화 같은데
Map<Value, Set<Key>>
너회가 통해 해결할 수 있는 기능을 하는 경우, 가치 매핑이라는 고유하지 않은 key-> (형상화 그 외). 그렇게 두 사람이 모든 솔루션을 사용하여 여기에 미세한 agent. 병합합니다 제안하세요 매핑하므로.
키 값을 사용하여 다음과 같은 코드를 사용하여 구할 수 있습니다.
ArrayList valuesList = new ArrayList();
Set keySet = initalMap.keySet();
ArrayList keyList = new ArrayList(keySet);
for(int i = 0 ; i < keyList.size() ; i++ ) {
valuesList.add(initalMap.get(keyList.get(i)));
}
Collections.sort(valuesList);
Map finalMap = new TreeMap();
for(int i = 0 ; i < valuesList.size() ; i++ ) {
String value = (String) valuesList.get(i);
for( int j = 0 ; j < keyList.size() ; j++ ) {
if(initalMap.get(keyList.get(j)).equals(value)) {
finalMap.put(keyList.get(j),value);
}
}
}
System.out.println("fianl map ----------------------> " + finalMap);
public static class SmartHashMap <T1 extends Object, T2 extends Object> {
public HashMap<T1, T2> keyValue;
public HashMap<T2, T1> valueKey;
public SmartHashMap(){
this.keyValue = new HashMap<T1, T2>();
this.valueKey = new HashMap<T2, T1>();
}
public void add(T1 key, T2 value){
this.keyValue.put(key, value);
this.valueKey.put(value, key);
}
public T2 getValue(T1 key){
return this.keyValue.get(key);
}
public T1 getKey(T2 value){
return this.valueKey.get(value);
}
}