code

Java hashMap 내용을 서로 다른 내용에 넣지 만 기존 키와 값을 바꾸지 않는 방법은 무엇입니까?

codestyles 2020. 10. 10. 10:05
반응형

Java hashMap 내용을 서로 다른 내용에 넣지 만 기존 키와 값을 바꾸지 않는 방법은 무엇입니까?


하나의 A HashMap에서 다른 하나의 B로 모든 키와 값을 복사해야하지만 기존 키와 값을 바꾸지는 않습니다.

그렇게하는 가장 좋은 방법은 무엇입니까?

대신 keySet을 반복하고 존재 여부를 확인하려고 생각했습니다.

Map temp = new HashMap(); // generic later
temp.putAll(Amap);
A.clear();
A.putAll(Bmap);
A.putAll(temp);

임시을 생성 할 의향이있는 것 같으 Map므로 다음과 같이하겠습니다.

Map tmp = new HashMap(patch);
tmp.keySet().removeAll(target.keySet());
target.putAll(tmp);

여기에 patch지도에 추가 할지도가 target있습니다.

Louis Wasserman 덕분 에 Java 8의 새로운 메소드를 활용하는 버전이 있습니다.

patch.forEach(target::putIfAbsent);

사용 구아바지도 가 더 당신이 달성하려고하는 분명한 만드는 방법 서명 당신이 한 줄에 그것을 할 수있는이지도의 차이를 계산하는 클래스의 유틸리티 방법 :

public static void main(final String[] args) {
    // Create some maps
    final Map<Integer, String> map1 = new HashMap<Integer, String>();
    map1.put(1, "Hello");
    map1.put(2, "There");
    final Map<Integer, String> map2 = new HashMap<Integer, String>();
    map2.put(2, "There");
    map2.put(3, "is");
    map2.put(4, "a");
    map2.put(5, "bird");

    // Add everything in map1 not in map2 to map2
    map2.putAll(Maps.difference(map1, map2).entriesOnlyOnLeft());
}

반복하고 추가하십시오.

for(Map.Entry e : a.entrySet())
  if(!b.containsKey(e.getKey())
    b.put(e.getKey(), e.getValue());

추가하려면 편집 :

a를 변경할 수있는 경우 다음을 수행 할 수도 있습니다.

a.putAll(b)

그리고 당신이 필요한 것을 정확히 가지고 있습니다. (모든 항목 b및 모든 항목에 a해당하지 않을 수 있습니다 b)


@erickson의 솔루션에서 맵 순서를 변경하면 단 한 줄로 만들 수 있습니다.

mapWithNotSoImportantValues.putAll( mapWithImportantValues );

이 경우 mapWithNotSoImportantValues의 값을 동일한 키가있는 mapWithImportantValues의 값으로 바꿉니다.


public class MyMap {

public static void main(String[] args) {

    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("key1", "value1");
    map1.put("key2", "value2");
    map1.put("key3", "value3");
    map1.put(null, null);

    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("key4", "value4");
    map2.put("key5", "value5");
    map2.put("key6", "value6");
    map2.put("key3", "replaced-value-of-key3-in-map2");
    // used only if map1 can be changes/updates with the same keys present in map2.
    map1.putAll(map2);

    // use below if you are not supposed to modify the map1.
    for (Map.Entry e : map2.entrySet())
        if (!map1.containsKey(e.getKey()))
            map1.put(e.getKey().toString(), e.getValue().toString());
    System.out.println(map1);
}}

Java 8에는 요구 사항을 충족하는이 API 메서드가 있습니다.

map.putIfAbsent(key, value)

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

참고URL : https://stackoverflow.com/questions/7194522/how-to-putall-on-java-hashmap-contents-of-one-to-another-but-not-replace-existi

반응형