티스토리 뷰

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<>(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);
	}

}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함