리팩토링(스프링기반)
Map 전체 내용을 읽을 때 Key, Value를 모두 사용한다면 "entrySet"을 사용하라
까오기
2019. 1. 8. 09:06
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)
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<>(m.keySet());
// Map에 value를 List 담기
List<String> list = new ArrayList<>(m.values());
list.stream().forEach(System.out::println);
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);
}
}