티스토리 뷰
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);
}
}'리팩토링(스프링기반)' 카테고리의 다른 글
| 동일 처리를 하는 catch문 합치기 (0) | 2019.01.08 |
|---|---|
| private method의 @Transactional 제거 (0) | 2019.01.08 |
| 오브젝트 복제하기 (0) | 2019.01.07 |
| 타입선언은 인터페이스로 하자 (0) | 2019.01.07 |
| Java class, method 선언 시 표현 순서 (0) | 2019.01.07 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 예제
- spring
- restful서비스
- mapToList
- AG-GRID
- 설정
- 타임리프
- 스프링
- cache
- sample
- 메시지
- ag grid
- RESTful
- REST
- 스프링부트
- Spring Boot
- mybatis
- SHEETJS
- oracle
- 샘플
- Javascript
- java
- 엑셀
- example
- listToMap
- 그리드
- UI
- springboot
- lombok
- thymeleaf
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
글 보관함