Modern Java Syntax and Coding Techniques Cheat Sheet
1. Sorting with Lambdas
- Sort 1D array (primitive):
Arrays.sort(arr);
- Sort 2D array by first column:
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
- Sort by first, then second if equal:
Arrays.sort(intervals, (a, b) -> {
if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
return Integer.compare(a[0], b[0]);
});
- Descending sort:
Arrays.sort(arr, (a, b) -> Integer.compare(b, a));
2. List to Array Conversions
- List<Integer> to int[]:
List<Integer> list = Arrays.asList(1, 2, 3);
int[] arr = list.stream().mapToInt(i -> i).toArray();
- List<int[]> to int[][]:
List<int[]> merged = new ArrayList<>();
return merged.toArray(new int[merged.size()][]);
3. Array to List Conversions
- int[] to List<Integer>:
int[] arr = {1, 2, 3};
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
- int[][] to List<int[]>:
int[][] arr = {{1, 2}, {3, 4}};
List<int[]> list = Arrays.asList(arr);
4. Custom Object Sorting
Modern Java Syntax and Coding Techniques Cheat Sheet
class Pair {
int start, end;
Pair(int s, int e) { start = s; end = e; }
}
List<Pair> list = new ArrayList<>();
Collections.sort(list, (a, b) -> Integer.compare(a.start, b.start));
5. Streams for Lists and Maps
- Filter + map:
list.stream()
.filter(s -> s.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
- Sort map by value:
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(entry -> ...);
6. Frequency Map Tricks
- Build frequency map:
Map<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray())
freq.put(c, freq.getOrDefault(c, 0) + 1);
- Sort by frequency:
freq.entrySet().stream()
.sorted((a, b) -> b.getValue() - a.getValue())
.forEach(entry -> ...);
7. PriorityQueue (Heap)
- Min heap:
PriorityQueue<Integer> pq = new PriorityQueue<>();
- Max heap:
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
Modern Java Syntax and Coding Techniques Cheat Sheet
- Custom objects:
PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> Integer.compare(a.end, b.end));
8. Subset / Combination Tricks
- Subsets using bitmask:
for (int i = 0; i < (1 << n); i++) {
List<Integer> subset = new ArrayList<>();
for (int j = 0; j < n; j++)
if ((i & (1 << j)) > 0) subset.add(nums[j]);
}
- Combinations via recursion:
void combine(int[] arr, int start, List<Integer> current) {
result.add(new ArrayList<>(current));
for (int i = start; i < arr.length; i++) {
current.add(arr[i]);
combine(arr, i + 1, current);
current.remove(current.size() - 1);
}
}
9. Useful ArrayList Tricks
List<Integer> list = new ArrayList<>();
list.add(5);
int last = list.get(list.size() - 1);
list.remove(list.size() - 1); // remove last element
10. Arrays.fill and Cloning
int[] arr = new int[10];
Arrays.fill(arr, -1); // Fill all with -1
int[] copy = arr.clone(); // Make a copy of array