Java List 정리 꿀팁: removeIf로 불필요한 요소 간단히 제거하기
List 에서 특정 조건 삭제하기 할 때 RemoveIf 괜찮은거 같아!
팝업공지를 위해 공지하고 싶은 것들을 DB에 관리 하고 있다. 각 공지 건들은 언제가지 공지해라 라는 finishtimestamp 를 저장한다. 해당 finishtimestamp 는 지나게 되면 사용자의 공지에 나오지 않으며 지금 시간이 해당 timestamp 를 지나있다면 ? 바로 DB에서 삭제를 하려고 한다!
removeIf로 삭제하기
원래라면 아래 처럼 작성 했을것이다. 리스트를 돌면서
1
2
3
4
5
6
List<Notification> notDeleteList = new ArrayList<Notification>();
for (Notification notification : totalNotificationList) {
if (System.currentTimeMillis() < notification.getFinishTimestamp())
notDeleteList.add(notification);
}
// 기존 List 대신 저장하는 로직
아니면 iterator를 돌면서 이렇게 짤수 있을 것이다.
1
2
3
4
5
6
Iterator<Notification> iterator = totalNotificationList.iterator();
while (iterator.hasNext()) {
Notification notification = iterator.next();
if (System.currentTimeMillis() > notification.getFinishTimestamp())
iterator.remove();
}
두가지 방법 모두 너무 코드가 길고 또 이해하는데에 처음 보는 사람이라면 어려울 수 있다. 하지만! 오늘 알아낸 removeIf 라는 방법은 정말! 너무너무 가독성이 좋고 사용하기도 쉬웠다! 위의 코드를 아래처럼 바꿀수 있다
1
2
3
totalNotificationList.removeif( notification -> {
return System.currentTimeMillis() > notification.getFinishTimestamp();
})
우와,,,, 앞으로 애용할 생각이다!
This post is licensed under CC BY 4.0 by the author.