2012-07-24 3 views
3
HashMap<Integer,Integer> hashmapsample= new HashMap<Integer, Integer>(); 

내가HashMap의 중복 키 값 쌍을 얻으려면 어떻게해야합니까?

(1 , 7) 
(2 , 4) 
(4 , 5) 
(3, 7) 

같은 값을 가질 수는 중복 키가있을 실 거예요. 중복 값만 발생할 수 있습니다.

중복 값이있는 (키, 값) 쌍을 선택하고 싶습니다.

중복 (키, 값)을 다른 해시 맵으로 얻으면 좋을 것입니다. 어떻게하면됩니까?

나는 당신이 중복 키를 가질 수 없습니다

(1 , 7) 
(3, 7) 
+0

명확하게 이해하지 못했습니다. –

+0

@ Meenakshi : 위 예제에서 중복 값이 ​​있으므로 (1,7) 및 (3,7)을 원하십니까? – Syam

+0

(3, 7)은 (는) 중복 값 7이므로 다른 해시 맵에서이 쌍 (3, 7)을 원합니다. 나는 그렇게 생각한다 –

답변

6

방법 :

좋아, 여기에 기본적으로 당신의 HashMap를 반대하는 일부 코드입니까?

public HashMap getDuplicateValues(HashMap in) 
{ 
    // Clone input HashMap because we're removing stuff from it 
    in = (HashMap)in.clone(); 
    HashMap rval = new HashMap(); 
    Object[] keys = in.keySet().toArray(); 

    // iterate through all keys 
    for(int x=0;x<keys.length;x++) { 
     Object value = in.get(keys[x]); 
     in.remove(keys[x]); 
     // if value is in input HashMap, store it in duplicate HashMap because it has another value 
     if(in.containsValue(value)) { 
     rval.put(keys[x],value); 
     } 
     // if value is in duplicate HashMap, store it also because it HAD another value earlier 
     if(rval.containsValue(value)) { 
     rval.put(keys[x],value); 
     } 
    } 

    return(rval); 
} 

이 메소드는 입력 HashMap에있는 모든 중복 값에 대해 키/값 쌍을 리턴합니다.


테스트 코드 :

HashMap map = new HashMap(); 

    map.put("1","2"); 
    map.put("2","1"); 
    map.put("3","8"); 
    map.put("4","4"); 
    map.put("5","6"); 
    map.put("6","8"); 
    map.put("7","3"); 
    map.put("8","4"); 
    map.put("9","4"); 

    HashMap dups = getDuplicateValues(map); 

    System.out.println("MAP = "+map); 
    System.out.println("DUP = "+dups); 

출력 :

MAP = {3=8, 2=1, 1=2, 7=3, 6=8, 5=6, 4=4, 9=4, 8=4} 
DUP = {3=8, 6=8, 4=4, 9=4, 8=4} 
+0

@Meenakshi이 코드를 사용해보십시오. – Azuu

+0

@ 존 Lin 감사합니다. 많이 .. – Meenakshi

+0

이 솔루션에 문제가 있습니까? 왜 downvote? –

1

출력을 기대합니다. 상자의 낱단 같이, 하나의 각각을위한 그들과 함께 생각하십시오. 상자 1에 망치, 상자 2에 키보드, 상자 3에 손전등, 상자 4에 다른 망치를 넣을 수 있습니다. 그러나 상자 1에는 두 개의 해머 또는 해머와 키보드를 넣을 수 없습니다. 한 가지를위한 공간이 있습니다. 이미 가득 찬 상자에 다른 것을 추가하려고하면 자동으로 꺼내어 버리고 오래된 것을 버립니다. 액세스 할 수있는 방법이 없습니다

나는이 질문을 잘못 해석했다고 생각합니다. 당신이 정확히 무엇을 검색/할려고하는지 더 잘 설명 할 수 있습니까? 이것에 대해

public static void main(String[] args) throws ParseException { 
    HashMap start = new HashMap(); 
    start.put(1, 7); 
    start.put(2, 4); 
    start.put(4, 5); 
    start.put(3, 7); 

    HashMap<Object, ArrayList<Object>> reversed = reverse(start); 

    //Some code to print out our results 
    Set<Entry<Object, ArrayList<Object>>> set = reversed.entrySet(); 

    for(Entry entry : set) { 
     System.out.println(entry.getKey() + ": " + entry.getValue()); 
     //if we want here, we can check if the size of the value (The 
    //ArrayList of old keys who has a value of this guy's key) is over 1, if so, 
    //there were duplicates of some value (stored to this entry's key) 
    } 
} 
public static HashMap<Object, ArrayList<Object>> reverse(HashMap map) { 
    HashMap<Object, ArrayList<Object>> newMap = 
      new HashMap<Object, ArrayList<Object>>(); 

    Set<Entry> set = map.entrySet(); 
    for(Entry entry : set) { 
     ArrayList list = new ArrayList(); 
     if(newMap.containsKey(entry.getValue())) { 
      list=newMap.get(entry.getValue()); 
     } 
     list.add(entry.getKey()); 
     newMap.put(entry.getValue(), list); 
    } 
    return newMap; 
} 
+0

나는 단지 성명을 발표했다. 그래서 그 명백한, 내가 그것을 의미 할 때 그것은 가치를위한 것이고 열쇠를위한 것이 아님을 의미한다. – Meenakshi

+0

그게 전부! 내가 사용합니다 .. 고마워요 @ Alex Coleman – Meenakshi

1
HashMap<Integer, Integer> sample = new HashMap<Integer, Integer>(); 
    Integer valueForSearch = 7; 
    HashMap<Integer, Integer> result = new HashMap<Integer, Integer>(); 
    for (Entry<Integer, Integer> entry : sample.entrySet()) { 
     if (entry.getValue().equals(valueForSearch)) { 
      result.put(entry.getKey(), entry.getValue()); 
     } 
    } 
+0

이것은 일반적인 코드가 아닙니다. 값이 7인지 알 수 있습니다. –

+0

@ Jin35 7이 두 번만 발생한다는 것을 모를 수도 있습니다. 3 회 5 회 또는 몇 번 다른 값이있을 수 있습니다. – Meenakshi

+0

그래,하지만 ** 모든 ** 결과를 얻으려면'HashMap >'이 될 것이다. – Jin35

0

그냥 윤곽을주고 ...

Object array[] = hashmapsample.keySet().toArray(); 
    for(int i=0;i<array.length();i++) 
    { 
     if(hashmapsample.containsValue(hashmapsample.get(array[i]){ 
    //Put that particular value in another hashmap here 
    }  
    } 

아이 .. 내가 더 자세한 답변을 찾을 수 이 게시물에 : D 조 내 무시 ...

관련 문제