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) |
---|---|---|---|---|---|
1 | 1 | 1 | 1 | 1 | 1 |
2 | 1 | 1 | 2 | 4 | 8 |
4 | 1 | 2 | 8 | 16 | 64 |
8 | 1 | 3 | 24 | 64 | 512 |
16 | 1 | 4 | 64 | 265 | 4096 |
1024 | 1 | 10 | 10240 | 1048576 | 1073741824 |
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:
get | contains | add | remove | |
---|---|---|---|---|
ArrayList | O(1) | O(n) | O(1) | O(n) |
HashSet | N/A | O(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; } } }