에르난 주연 :
모든 클라이언트는 날짜와 아이디, 많은 송장을 가지고
날짜별로 송장의 hasmap의, id로 고객의 해시 맵으로 저장
HashMap<LocalDateTime, Invoice> allInvoices = allInvoicesAllClients.get(id);
if(allInvoices!=null){
allInvoices.put(date, invoice); //<---REPEATED CODE
}else{
allInvoices = new HashMap<>();
allInvoices.put(date, invoice); //<---REPEATED CODE
allInvoicesAllClients.put(id, allInvoices);
}
자바 솔루션을 사용하는 것 같다 getOrDefault
HashMap<LocalDateTime, Invoice> allInvoices = allInvoicesAllClients.getOrDefault(
id,
new HashMap<LocalDateTime, Invoice> (){{ put(date, invoice); }}
);
GET가 null가 아닌 경우에, 여전히도 여전히 필요하다 "allInvoicesAllClients"에 데이터를 추가, 실행 (날짜, 송장)을 넣어합니다. 그것은 보이지 않는다 그래서에 많은 도움이됩니다.
야곱 G. :
이것은을위한 훌륭한 사용 사례입니다 Map#computeIfAbsent
. 당신의 조각은 본질적으로 동일합니다 :
allInvoicesAllClients.computeIfAbsent(id, key -> new HashMap<>()).put(date, invoice);
경우 id
에 키와 존재하지 않는 allInvoicesAllClients
, 그것은에서 매핑을 만듭니다 id
새에 HashMap
새를 반환합니다 HashMap
. 경우 id
키로 존재, 그것은 기존 돌아갑니다 HashMap
.