티스토리 뷰

Iterate over the "entrySet" instead of the "keySet".

Map에 있는 키 값을 꺼내서 루프를 돌리는데 만약 key값 이외 value도 필요하다며 keySet을 사용하지 말고 entrySet을 사용하라.  

"entrySet()" should be iterated when both the key and value are needed (squid:S2864)

CODE_SMELL Code smell MAJOR Major

When only the keys from a map are needed in a loop, iterating the keySet makes sense. But when both the key and the value are needed, it's more efficient to iterate the entrySet, which will give access to both the key and value, instead.

Noncompliant Code Example

public void doSomethingWithMap(Map<String,Object> map) {
  for (String key : map.keySet()) {  // Noncompliant; for each key the value is retrieved
    Object value = map.get(key);
    // ...
  }
}

Compliant Solution

public void doSomethingWithMap(Map<String,Object> map) {
  for (Map.Entry<String,Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
  }
}

Map에 값을 List에 담기 예제 

// Map에 Key를 List에 담기

List<String> list = new ArrayList<String>(m.keySet());

// Map에 value를 List 담기 

List<String> list = new ArrayList<String>(m.values());

List를 Map에 담기, Flyweight Pattern  

@Component
public class ServiceFactory {

	private Map<String, ServiceIF> serviceMap;

	public ServiceFactory(@Autowired List<ServiceIF> services){
		this.serviceMap = testServices.stream().collect(Collectors.toMap(ServiceIF::getServiceId, item -> item));
	}

	public ServiceIF getService(String serviceId) {
		return testServiceMap.get(serviceId);
	}

}
댓글
댓글쓰기 폼