웹 개발

Copying a HashMap

노루아부지 2021. 7. 31. 23:28
  1. 생성자를 사용한 복사
    HashMap<String, String> src = new HashMap<>();
    src.put("name", "hong");
    src.put("age", "19");
    
    HashMap<String, String> dst = new HashMap<>(src);​
  2. clone()을 사용한 복사
    HashMap<String, String> dst = (HashMap<String, String>)src.clone();​
  3. putAll()을 사용한 복사
    HashMap<String, String> dst = new HashMap<>();
    dst.putAll(src);​
  4. Map.Entry를 사용한 복사
    HashMap<String, String> dst = new HashMap<>();
    
    for(Map.Entry<String, String> entry : src.entrySet()) {
      dst.put(entry.getKey(), entry.getValue());
    }​
  5. keySet()을 사용한 복사
    HashMap<String, String> dst = new HashMap<>();
    
    for (String key : src.keySet()) {
      dst.put(key, src.get(key));
    }​
  6. Java 8 Stream API를 사용한 복사
    Set<Map.Entry<String, String>> entries = src.entrySet();
    HashMap<String, String> dst = (HashMap<String, String>) entries.stream()
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));​
728x90
loading