본문 바로가기

알고리즘

java HashMap

728x90

난 항상 향상된 for문을 사용하는 편이었는데 람다식에 좀 더 익숙해질 필요가 있는듯

 

//key출력

valuevalues.forEach(value -> System.out.println(value)); 

 

//key와 value출력

productPrice.forEach((key, value) -> { System.out.print("key: "+ key); System.out.println(", Value: "+ value); }); 


keySet()만 또 익숙했었는데!

키와 값이 모두 필요할 땐 entryset()을 이용하자.

 

compute() ,computeIfPresent()

putIfAbsent() , computeIfAbsent() 


 

 

사실 이거때문에 이 글 씀

getOrDefault

찾는 키가 존재하면 해당 키의 값 반환, 없다면 기본 값 반환

 

for (String player : participant) hm.put(player, hm.getOrDefault(player, 0) + 1);

hm에 key가 없다면 0, 있다면 반환 후 +1

 


자바8에서 함께 추가된 내용들

compute()

computeIfPresent()

putIfAbsent()

computeIfAbsent()