Misc
Array
To initialise array of custom class
Entry<K, V>[] data = (Entry<K, V>[]) Array.newInstance(Entry.class, capacity);
When accessing an element from array like this without intialising, depends on the thing it will be different, for example.
int[] intergers = new int[10];
integers[0] // == 0
String[] strings = new String[10];
System.out.println(strings[2]); // == null
Object[] objects = new Object[10];
System.out.println(objects[2]); // == null
ArrayList
If we do the same for arraylist however we get index out of bound
List<Integer> test = new ArrayList<>(100);
System.out.println(test.get(3)); // IndexOutOfBoundException
Don't use toList()
as it returns an unmodifiable list. Use .collect(Collectors.toList())
Array vs ArrayList
Try use ArrayList as possible, if need a fixed size list, use
List<Entry<K, V>> entries = Collections.nCopies(capacity, null);
List<Entry<K, V>> fixedSizeList = entries.stream().collect(Collectors.toList());
this is because nCopies
will return immutableList
It's either that or
new ArrayList<>(Collections.nCopies(100, null));
or
new ArrayList<>(new Integer[100]) // 100 element of Integer[] array
natural
(a, b) -> a - b
5,4,3,2,1
reverse
(b, a) -> b - a
1,2,3,4,5
Nested comparator
Comparator<Candidate> compareVotes = (a, b) -> b.votes() - a.votes();
Comparator<Candidate> compareNames = (a, b) -> a.name().compareTo(b.name());
sortedCandidates = new PriorityBlockingQueue<>(10, compareVotes.thenComparing(compareNames));
Modifiable 2D ArrayList
List<List<Integer>> arrays = Stream.of(
List.of(1, 1, 1, 1, 1),
List.of(0, 1, 0, 0, 0),
List.of(0, 1, 0, 1, 1),
List.of(0, 1, 1, 1, 1)
).map(ArrayList::new).collect(Collectors.toList());
BinarySearch
List<Integer> integerList = List.of(1,2,3,4,5,6,7,8,9);
System.out.println(Collections.binarySearch(integerList, 9));
Sort but return new
List<Integer> integerList = List.of(5,3,1,9,7,10,13);
System.out.println(integerList.stream().sorted().collect(Collectors.toList()));
BinarySearch
public static int binarySearch(List<Integer> array, Integer target) {
int startIndex = 0;
int endIndex = array.size() - 1;
while (startIndex < endIndex) {
int middleIndex = startIndex + (endIndex - startIndex) / 2;
if (array.get(middleIndex) >= target) {
endIndex = middleIndex;
} else {
startIndex = middleIndex + 1;
}
}
return startIndex;
}
SortedSet
public class SetDemo {
public static void main(String[] args) {
SortedSet<Integer> sortedSet = new TreeSet<>();
Set<Integer> set = new HashSet<>();
Stream.of(5,5,3,2,9,15,-30).forEach(sortedSet::add);
Stream.of(5,5,3,2,9,15,-30).forEach(set::add);
System.out.println("sortedSet: " + sortedSet);
System.out.println("set: " + set);
}
}
sortedSet: [-30, 2, 3, 5, 9, 15]
set: [2, 3, 5, 9, -30, 15]
For SortedSet
, time complexity is log(n)
for everything since it's a Tree
For Set
it's O(1)