Hash Set vs Array List

title-img-nlogn-1
Recalling a Big-O notation in (CS) Computer Science major course I have taken in College:

O(n)O(1)O(log n)O(n log n)O(n^2)O(n^3)
111111
211248
41281664
8132464512
1614642654096
10241101024010485761073741824

In Biz apps, you need to use List object all the time. And often has performance issue. It’s better to use some other data structure, such as Map object because HashSet is much faster compared to ArrayList:
getcontainsaddremove
ArrayListO(1)O(n)O(1)O(n)
HashSetN/AO(1)O(1)O(1)

Note: HashSet does not provide “get” method, but as long as “contains” method is available, we know what element we need

Here is how to work on:
First, converting ArrayList to HashSet

private Set<String> convertToHashSet(List<Map<String, Object>> listToDelete) {
	Set<String> set = new HashSet<String>();
	for (Map<String, Object> obj : listToDelete) {
		set.add(new String("test"));
	}
	return set;
}

Or just simply set a list as constructor’s parameter:

private Set<String> convertToHashSetDirectory(List<String> list) {
	return new HashSet<String>(list);
}

“contains” with for loop version:

private void hashSetDemoFor(Set<String> setOfMdseOnScreen, Set<String> setOfMdseAcctTo) {
	Map<String, Long> resultMap = new HashMap<String, Long>();
	for (String mdseAcctTo : setOfMdseAcctTo) {
		if (setOfMdseOnScreen.contains(mdseAcctTo)) {
			// Do something
			continue;
		}
	}
}

“contains” with while loop version:

private void hashSetDemoWhile(Set<String> setOfMdseOnScreen, Set<String> setOfMdseAcctTo) {
	Iterator<String> itr = setOfMdseOnScreen.iterator();
	while (itr.hasNext()) {
		String mdseOnScreen = itr.next();
		if (setOfMdseAcctTo.contains(mdseOnScreen)) {
			// Do something
			continue;
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.